Write a Python program to reverse each word in file.

Questions & AnswersCategory: PythonWrite a Python program to reverse each word in file.
1 Answers
Lokesh Kumar Staff answered 2 years ago

Solution:

https://gist.github.com/LokeshKumarES/646649e6ba7e6d966809e3f7dc14dc59

# text1.txt content
'''
hello easter science
how are you
we assist you to choose the best
'''

with open('test1.txt', 'r') as r_file:
    x = r_file.readlines()
res = []
for i in x:
    line_split = i.split()
    y = list(reversed(line_split))
    res.append(' '.join(y))

with open('text2.txt', 'w') as w_file:
    for j in res:
        w_file.write(j+'\n')