Python string replaces broken newlines

I have a file with keywords, I just wanted to replace the new lines with commas

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

tried all options \r\n

+4
source share
5 answers

Do not forget that this is Python! Always look for an easy way ...

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

+5
source

Your code should work as written. However, here is another way.

Let Python break you lines ( for line in f ). Use open instead of file . Use with , so you do not need to manually close the file.

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

I just tried this and it works for me. What does your file look like?

My temp.txt file looked like this:

a
b
with
d
e

and my python file had this code:

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

This was my conclusion:

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

0
source

The code you wrote works for me in the test file I created.

Are you trying to write the results to a file?

You can try to look at the input file in a hex editor to see the end of the line.

0
source

Do you want to replace the actual contents of the file? Like this:

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

All Articles