5

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

1
  • 2
    As posted, your code is fine. The most common mistake with replace() is that people forget to assign the result: s.replace(old, new) instead of s=s.replace(old, new). Commented Oct 19, 2011 at 18:32

8 Answers 8

5

Don't forget, this is Python! Always look for the easy way...

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'm pretty sure "pythonic" does not mean "the shortest one-liner possible". Also, your example is not even running against a file.
2

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!

Comments

0

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

My "temp.txt" file looked like this:

a
b
c
d
e

and my python file had this code:

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

This was my output:

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

Comments

0

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.

Comments

0

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)

Comments

0

I've just had the same problem and this was the solution to it:

phones = arr[8].replace("\\n", "|")

Comments

0

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...

Comments

0

Search on double slash n instead of \n. That cost hours of my life. This website even changes it to \n when I tried to paste it. The combo that shall not be spoken. ""+""+"n" would be the string combo to try to explain it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.