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