我有一个单词列表,其中包含用于分隔每个新字母的返回.有没有办法在Python中使用文件I/O以编程方式删除每个返回?
编辑:我知道如何操纵字符串来删除返回.我想物理编辑该文件,以便删除这些返回.
我正在寻找这样的东西:
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)
Run Code Online (Sandbox Code Playgroud)
aqu*_*qua 18
>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
Run Code Online (Sandbox Code Playgroud)
这基本上是说"切断字符串中的最后一件事"这:
是"切片"操作符.阅读它是如何工作的,因为它非常有用,这是一个好主意.
编辑
我刚看了你更新的问题.我想我现在明白了.你有一个文件,像这样:
aqua:test$ cat wordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
Run Code Online (Sandbox Code Playgroud)
而你想摆脱空行.您不是在读取文件时修改文件,而是创建一个新文件,您可以将旧文件中的非空行写入,如下所示:
# 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()
Run Code Online (Sandbox Code Playgroud)
你应该得到:
aqua:test$ cat newwordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
Run Code Online (Sandbox Code Playgroud)
如果你想要的东西
TestingThisWordlistWithReturnsBetweenLines
Run Code Online (Sandbox Code Playgroud)
只是评论出来
wf.write('\n')
Run Code Online (Sandbox Code Playgroud)
Sen*_*ran 16
您可以使用字符串的rstrip方法从字符串中删除换行符.
>>> 'something\n'.rstrip('\r\n')
>>> 'something'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
72044 次 |
最近记录: |