我有一个关键字文件,我只想用逗号替换掉换行符。
print file("keywords.txt", "r").read().replace("\n", ", ")
尝试了所有的 \r\n
变体。
不要忘记,这是 Python!总是寻找简单的方法...
', '.join(mystring.splitlines())
您的代码 应该 按照书写方式运行。不过,这里有另一种方法。
让Python为您拆分这些行(for line in f
)。使用open
而不是file
。使用with
,这样您就不需要手动关闭文件。
with open("keywords.txt", "r") as f:
print ', '.join(line.rstrip() for line in f) # don't have to know line ending!
我刚刚尝试了这个方法,对我有效。你的文件是什么样子的?
我的 "temp.txt" 文件长这样:
a
b
c
d
e
我的 Python 文件包含以下代码:
print file("temp.txt", "r").read().replace("\n", ", ")
>python temp_read.py
a, b, c, d, e,
你想要替换实际文件内容吗?像这样:
newContent = file("keywords.txt", "r").read().replace("\r", "").replace("\n", ", ")
open("keywords.txt", "w").write(newContent)
我刚刚遇到了同样的问题,这是解决方法:
phones = arr[8].replace("\\n", "|")
你写的代码在我创建的测试文件中运行良好。
你是想将结果写回文件吗?
你可以尝试在十六进制编辑器中查看输入文件以查看行结尾。
new_text = ",".join(text.split("\n"))
text = text.replace("\\n", ",")
text = text.replace("\n", ",")