📌  相关文章
📜  用于反转文件内容并将其存储在另一个文件中的Python程序

📅  最后修改于: 2022-05-13 01:55:03.432000             🧑  作者: Mango

用于反转文件内容并将其存储在另一个文件中的Python程序

给定一个文本文件。任务是将内容从输入文件反转并存储到输出文件。
这种反转可以以两种类型进行。

  • 完全反转:在这种类型的反转中,所有内容都被反转。
  • 字对字倒转:在这种倒转中,最后一个字在前,第一个字在最后一个位置。

示例 1:完全反转

Input: Hello Geeks
       for geeks!
        

Output:!skeeg rof
        skeeG olleH
        


示例 2:单词到单词反转

Input: 
        Hello Geeks
        for geeks!

Output:
         geeks! for
         Geeks Hello


示例 1:完全反转
文本文件:

python-反向文件输入

Python
# Open the file in write mode
f1 = open("output1.txt", "w")
  
# Open the input file and get 
# the content into a variable data
with 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 string
data_1 = data[::-1]
  
# Now we will write the fully reverse 
# data in the output1 file using 
# following command
f1.write(data_1)
  
f1.close()


Python3
# Open the file in write mode
f2 = open("output2.txt", "w")
  
  
# Open the input file again and get 
# the content as list to a variable data
with open("file.txt", "r") as myfile:
    data = myfile.readlines()
  
# We will just reverse the 
# array using following code
data_2 = data[::-1]
  
# Now we will write the fully reverse 
# list in the output2 file using 
# following command
f2.writelines(data_2)
  
f2.close()


输出:

python-reverse-file-output-1

示例 2:颠倒行的顺序。我们将使用上面的文本文件作为输入。

Python3

# Open the file in write mode
f2 = open("output2.txt", "w")
  
  
# Open the input file again and get 
# the content as list to a variable data
with open("file.txt", "r") as myfile:
    data = myfile.readlines()
  
# We will just reverse the 
# array using following code
data_2 = data[::-1]
  
# Now we will write the fully reverse 
# list in the output2 file using 
# following command
f2.writelines(data_2)
  
f2.close()

输出:

python-reverse-file-output-2