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

标签 python file reverse

<分区>

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

最佳答案

以相反的顺序循环遍历行。这里有几种方法。

使用范围:

lines = infile.readlines()
for i in range(len(l)-1,-1, -1):
     print l[i]

切片符号:

for i in l[::-1]:
    print i

或者,只需使用内置的 reversed 函数:

lines = infile.readlines()
for i in reversed(lines):
    newcontent.append(i)

关于python - 在python上以相反的顺序读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803801/

相关文章:

python - 如何从模型生成的表单中指定我想要的小部件(例如 TextArea 而不是简单的文本输入)? flask SQLAlchemy WTForms

python - 根据值返回颜色名称的优雅方式

Java - 如何从 Java 文件夹中删除文件?

java - 返回字符串结果不正确

c++ - 为什么 std::reverse 需要双向迭代器?

java - java中分割数组的索引并将其存储到一个新数组中

python - 如何在 Odoo 10 中从 Python 返回现有的 ir.actions.act_window?

python - 有使用 Pypy 的大项目吗?

c# - 以编程方式在联机和脱机之间移动 OneDrive 文件

c# - 查找文件的路径