简体   繁体   English

Python字符串替换不工作的新行

[英]Python string replace not working new lines

I have a keywords file I just wanted to replace the new lines with commas 我有一个关键字文件,我只想用逗号替换新行

print file("keywords.txt", "r").read().replace("\n", ", ")

tried all variations of \\r\\n 尝试了\\r\\n所有变体

Don't forget, this is Python! 别忘了,这是Python! Always look for the easy way... 一直在寻找简单的方法......

', '.join(mystring.splitlines()) ','。join(mystring.splitlines())

Your code should work as written. 您的代码应该按照书面形式运行 However, here's another way. 但是,这是另一种方式。

Let Python split the lines for you ( for line in f ). 让Python为你分割行( for line in f )。 Use open instead of file . 使用open而不是file Use with so you don't need to close the file manually. 使用with因此您无需手动关闭文件。

with open("keywords.txt", "r") as f:
    print ', '.join(line.rstrip() for line in f) # don't have to know line ending!

I just tried this and it works for me. 我刚试过这个,它对我有用。 What does your file look like? 你的文件是什么样的?

My "temp.txt" file looked like this: 我的“temp.txt”文件看起来像这样:

a 一个
b b
c C
d d
e Ë

and my python file had this code: 我的python文件有这个代码:

print file("temp.txt", "r").read().replace("\n", ", ")

This was my output: 这是我的输出:

>python temp_read.py > python temp_read.py
a, b, c, d, e, a,b,c,d,e,

The code you wrote works for me in a test file I created. 您编写的代码在我创建的测试文件中为我工作。

Are you trying to write the results back to a file? 您是否尝试将结果写回文件?

You could try looking at the input file in a hex editor to see the line endings. 您可以尝试在十六进制编辑器中查看输入文件以查看行结尾。

Did you want to replace the actual file contents? 您想要替换实际的文件内容吗? Like this: 像这样:

newContent = file("keywords.txt", "r").read().replace("\r", "").replace("\n", ", ")
open("keywords.txt", "w").write(newContent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM