Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types.
Full reversing: In this type of reversing all the content gets reversed.
Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.
Example 1: Full Reversing
Input: Hello Geeks
for geeks!
Output: !skeeg rof
skeeG olleH
Example 2: Word to word reversing
Input:
Hello Geeks
for geeks!
Output:
geeks! for
Geeks Hello
Example 1: Full Reversing Text file:
Python
f1 = open("output1.txt", "w")
with open("file.txt", "r") as myfile:
data = myfile.read()
data_1 = data[::-1]
f1.write(data_1)
f1.close()
Output:
Time complexity: O(n), where n is the length of the input file “file.txt”.
Auxiliary space: O(n), where n is the length of the input file “file.txt”.
Example 2: Reversing the order of lines. We will use the above text file as input.
Python3
f2 = open("output2.txt", "w")
with open("file.txt", "r") as myfile:
data = myfile.readlines()
data_2 = data[::-1]
f2.writelines(data_2)
f2.close()
Output:
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
20 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...