Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reverse a txt file in python 3.8?

data = data2 = data3 = ""

with open('pushkin.txt', encoding='utf-8', mode='r') as fp:
    data = fp.read()

with open('romeo.txt', encoding='utf-8', mode='r') as fp:
    data2 = fp.read()
with open('byron.txt', encoding='utf-8', mode='r') as fp:
    data3 = fp.read()


data += "\n"
data += data2 + data3

with open('poems.txt', 'w', encoding='utf-8') as fp:
    fp.write(data)

With this code, I have transferred three text files into one.
Now I need to turn over text in that file, like this:

ABC       CDA
BCA  -->  BCA
CDA       ABC

but I don’t know how. I thought using reverse() or reversed(), but that makes it just from
abc to cba

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use reverse() to reverse the order of elements in a list after saving all the contents as list type to data variable, not the specific string, as follows:

data = []

with open('1.txt', encoding='utf-8', mode='r') as fp: # ABC
    data += fp.readlines()
    # data -> ['ABC\n']

with open('2.txt', encoding='utf-8', mode='r') as fp: # BCA
    data += fp.readlines()
    # data -> ['ABC\n', 'BCA\n']

with open('3.txt', encoding='utf-8', mode='r') as fp: # CDA
    data += fp.readlines()
    # data -> ['ABC\n', 'BCA\n', 'CDA\n']

data.reverse() # data becomes ['CDA\n', 'BCA\n', 'ABC\n']

with open('result.txt', 'w', encoding='utf-8') as fp:
    fp.write("".join(data))
# result.txt
CDA
BCA
ABC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading