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
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
Don't forget, this is Python! Always look for the easy way...
', '.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). Use open instead of file. Use with so you don't need to close the file manually.
with open("keywords.txt", "r") as f:
print ', '.join(line.rstrip() for line in f) # don't have to know line ending!
I had this problem too and solve it with :
new_text = ",".join(text.split("\n"))
My "\n" wasn't interpreted in the same way between my unit test (with str as input) and my integration test (with file reading import as input), so str.replace("\n", ",") didn't work with both tests.
EDIT => With both this works too :
text = text.replace("\\n", ",")
text = text.replace("\n", ",")
I don't know why is it different between file and str input...