Python 在文件输出中删除换行符/回车
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4791080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete newline / return carriage in file output
提问by Parseltongue
I have a wordlist that contains returns to separate each new letter. Is there a way to programatically delete each of these returns using file I/O in Python?
我有一个单词表,其中包含用于分隔每个新字母的返回值。有没有办法在 Python 中使用文件 I/O 以编程方式删除这些返回中的每一个?
Edit: I know how to manipulate strings to delete returns. I want to physically edit the file so that those returns are deleted.
编辑:我知道如何操作字符串来删除返回值。我想对文件进行物理编辑,以便删除这些返回。
I'm looking for something like this:
我正在寻找这样的东西:
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)
采纳答案by aqua
>>> string = "testing\n"
>>> string
'testing\n'
>>> string = string[:-1]
>>> string
'testing'
This basically says "chop off the last thing in the string" The :is the "slice" operator. It would be a good idea to read up on how it works as it is veryuseful.
这基本上是说“砍掉字符串中的最后一件事”。这:是“切片”运算符。阅读它的工作原理是个好主意,因为它非常有用。
EDIT
编辑
I just read your updated question. I think I understand now. You have a file, like this:
我刚刚阅读了您更新的问题。我想我现在明白了。你有一个文件,像这样:
aqua:test$ cat wordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
and you want to get rid of the empty lines. Instead of modifying the file while you're reading from it, create a new file that you can write the non-empty lines from the old file into, like so:
你想摆脱空行。不要在读取文件时修改文件,而是创建一个新文件,您可以将旧文件中的非空行写入其中,如下所示:
# 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()
You should get:
你应该得到:
aqua:test$ cat newwordlist.txt
Testing
This
Wordlist
With
Returns
Between
Lines
If you want something like
如果你想要类似的东西
TestingThisWordlistWithReturnsBetweenLines
just comment out
只是注释掉
wf.write('\n')
回答by Senthil Kumaran
回答by Jakob Bowyer
The most efficient is to not specify a strip value
最有效的是不指定条带值
'\nsomething\n'.split()will strip all special characters and whitespace from the string
'\nsomething\n'.split()将从字符串中去除所有特殊字符和空格
回答by jfs
Remove empty lines in the file:
删除文件中的空行:
#!/usr/bin/env python
import fileinput
for line in fileinput.input("wordlist.txt", inplace=True):
if line != '\n':
print line,
The file is moved to a backup file and standard output is directed to the input file.
文件被移动到备份文件,标准输出被定向到输入文件。
回答by Venu Murthy
simply use, it solves the issue.
简单使用,它解决了问题。
string.strip("\r\n")
回答by eatkimchi
'whatever\r\r\r\r\r\r\r\r\n\n\n\n\n'.translate(None, '\r\n')
returns
回报
'whatever'

