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
You are facing this issue because you are using the replace method incorrectly. When you call the replace method on a string in python you get a new string with the contents replaced as specified in the method call. You are not storing the modified string but are just using the unmodified string.
replace() method returns a copy of a string. This means that the old substring remains the same, but a new copy gets created – with all of the old text having been replaced by the new text.
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.
Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With