Skip to main content
 首页 » 编程设计

python之在python上以相反的顺序读取文件

2025年05月04日11lautakyan007

<分区>

import os.path 
try: 
    file1=input("Enter input file: ") 
    infile=open(filename1,"r") 
    file2=input("Enter output file: ") 
    while os.path.isfile(file2): 
        file2=input("File Exists! Enter new name for output file: ") 
    ofile=open(file2, "w") 
    content=infile.read() 
    newcontent=content.reverse() 
    ofile.write(newcontent)     
 
except IOError: 
    print("Error") 
 
else: 
    infile.close() 
    ofile.close() 

我使用这段代码是否正确?我似乎找不到将输入文件中的行反转为输出文件的方法。

输入示例

cat dog house animal 
 
plant rose tiger tree 
 
zebra fall winter donkey 

输出示例

zebra fall winter donkey 
 
plant rose tiger tree 
 
cat dog house animal