Page Contents
In this tutorial we will learn how to Write a Python program to reverse each word in a text file. Here we will use a file named secret_societies.txt . Contents of the file is shown below using an image –
![](https://i0.wp.com/www.codingconception.com/wp-content/uploads/2022/02/old.png?resize=427%2C120&ssl=1)
Steps to reverse each word in a text file
- First we will open the file in “r” mode , read all the content and store it in a variable
- Then using
split()
method we will create a list from the string - After that we will iterate the list and reverse each word using slicing
- Then using
join()
method we will convert the list into a string - Then we will open the file in “w” mode and write the string to it .
Write Python program to reverse each word in secret societies.txt file
# opening the file in read mode
with open("secret_societies.txt","r") as fp:
# creating a list from the string
contents=fp.read().split()
# reversing each word(element) of the list
for number in range(len(contents)):
contents[number]=contents[number][::-1]
# creating a string from the list
contents=(" ").join(contents)
# opening the file in write mode and write the content
with open("secret_societies.txt","w") as fp:
fp.write(contents)
![](https://i0.wp.com/www.codingconception.com/wp-content/uploads/2022/02/new.png?resize=411%2C108&ssl=1)
- In the above code first we have opened the file in “r” mode . Then using
read()
andsplit()
method we have created a list and stored it incontents
variable . Now value of contents variable is['Python', 'is', 'a', 'popular', 'programming', 'language', '.']
- Then we have iterated the list and using Python slicing reversed each word in the list . Now value of contents variable is
['nohtyP', 'si', 'a', 'ralupop', 'gnimmargorp', 'egaugnal', '.']
- Now using
join()
method we have converted the list into a string . - After that we have opened the same file in “w” mode and write the string to it .
Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .