在文件输出中删除换行符 / 回车符
我有一个单词列表,里面用换行符来分隔每个新字母。请问有没有办法用Python的文件输入输出功能,程序化地删除这些换行符呢?
补充说明:我知道怎么处理字符串来删除换行符,但我想要的是直接修改文件,让那些换行符真的被删除。
我想要的效果大概是这样的:
wfile = open("wordlist.txt", "r+")
for line in wfile:
if len(line) == 0:
# note, the following is not real... this is what I'm aiming to achieve.
wfile.delete(line)
7 个回答
3
最有效的方法是不指定任何去除的值。
'\nsomething\n'.split()
这个代码会把字符串中的所有特殊字符和空白都去掉。
20
你可以使用字符串的 rstrip 方法来去掉字符串末尾的换行符。
>>> 'something\n'.rstrip('\r\n')
>>> 'something'
24
>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
这段话的意思是“把字符串最后的部分去掉”。这里的:
是一个“切片”操作符。了解它的工作原理是个好主意,因为它非常有用。
编辑
我刚刚看了你更新的问题。现在我明白了。你有一个文件,像这样:
aqua:test$ cat wordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
你想去掉空行。在读取文件的时候,不要直接修改它,而是创建一个新文件,把旧文件中非空的行写进去,像这样:
# script
rf = open("wordlist.txt")
wf = open("newwordlist.txt","w")
for line in rf:
newline = line.rstrip('\r\n')
wf.write(newline)
wf.write('\n') # remove to leave out line breaks
rf.close()
wf.close()
你应该得到:
aqua:test$ cat newwordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
如果你想要类似这样的结果
TestingThisWordlistWithReturnsBetweenLines
只需把
wf.write('\n')