umpalumpa__
umpalumpa__

Reputation: 93

Keeping format of text (.txt) files when reading and rewriting

I have a .txt file containing formatting elements as \n for line breaks which I want to read and then rewrite its data until a specific line back to a new .txt file. My code looks like this:

with open (filename) as f:    
    content=f.readlines()

with open("lf.txt", "w") as file1:
    file1.write(str(content))
    file1.close

The output file lf.txt is produced correctly but it throws away the formatting of the input file. Is there a way to keep the formatting of file 1 when rewriting it to a new file?

Upvotes: 1

Views: 2022

Answers (1)

Israel Unterman
Israel Unterman

Reputation: 13510

You converted content to a string, while it's really a list of strings (lines).

Use join to convert the lines back to a string:

file1.write(''.join(content))

join is a string method, and it is activated in the example from an empty string object. The string calling this method is used as a separator for the strings joining process. In this situation we don't need any separator, just joining the strings.

Upvotes: 3

Related Questions