Steven Lindsey
Steven Lindsey

Reputation: 3

Reversing a txt File in python

Assume you are given a file called newText.txt which contains the lines: line 1 line 2 line 3

Write a python program that reads the data from newText.txt and writes a new file called newerText.txt in the following format: line 3 Python Inserted a new line line 2 line 1

I can get it reversed but the line 2 and line 3 are in the same line. I also need help appending the new line between line 2 and line 3. Input

lines = []
with open('text.txt') as f:
    lines = f.readlines()

with open('newtext.txt', 'w') as f:
    for line in reversed(lines):
        f.write(line)

Output

line3line2

line1

Upvotes: 0

Views: 49

Answers (1)

TerryA
TerryA

Reputation: 60004

If you look into what text.txt actually is, it's probably something like this:

line1\nline2\nline3

Notice how each line is divided by a new line character (\n). This means the last line doesn't have a new line at the end of it, so when you write it to newText.txt, it won't have a newline.

What you can do is strip away all possible new lines, then add one yourself:

with open('newtext.txt', 'w') as f:
    for line in reversed(lines):
        f.write(line.strip() + "\n")

Upvotes: 1

Related Questions