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 Lazyroar!
Output:!skeeg rof
skeeG olleH
Example 2: Word to word reversing
Input:
Hello Geeks
for Lazyroar!
Output:
Lazyroar! for
Geeks Hello
Example 1: Full Reversing
Text file:
Python
# Open the file in write modef1 = open("output1.txt", "w")# Open the input file and get# the content into a variable datawith open("file.txt", "r") as myfile: data = myfile.read()# For Full Reversing we will store the# value of data into new variable data_1# in a reverse order using [start: end: step],# where step when passed -1 will reverse# the stringdata_1 = data[::-1]# Now we will write the fully reverse# data in the output1 file using# following commandf1.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
# Open the file in write modef2 = open("output2.txt", "w")# Open the input file again and get# the content as list to a variable datawith open("file.txt", "r") as myfile: data = myfile.readlines()# We will just reverse the# array using following codedata_2 = data[::-1]# Now we will write the fully reverse# list in the output2 file using# following commandf2.writelines(data_2)f2.close() |
Output:

