删除文件输出中的换行符/回车符

2024-06-28 19:51:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个单词表,其中包含分隔每个新字母的返回。有没有办法使用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)

Tags: 文件字符串txt编辑is编程字母方式
3条回答

最有效的方法是不指定条带值

'\nsomething\n'.split()将从字符串中除去所有特殊字符和空白

>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'

这基本上是说“切掉字符串中的最后一个东西”:是“slice”运算符。阅读它的工作原理是个好主意,因为它非常有用。

编辑

我刚看了你最新的问题。我想我现在明白了。你有一个文件,像这样:

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')

可以使用字符串的rstrip方法从字符串中删除换行符。

>>> 'something\n'.rstrip('\r\n')
>>> 'something'

相关问题 更多 >