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

在python上以相反的顺序读取文件,python,file,reverse,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 f

我的代码正确吗?我似乎找不到一种方法将输入文件中的行反转为输出文件

输入例如

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
这应该行得通

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

range(0,len(lines),-1)
应该是
range(len(lines)-1,-1,-1)
。在Python中,要在列表上反转,常用的范例是对行中的i[::-1]使用
而不是
range
循环。谢谢大家!修复了它。
reverse()
是一个就地操作-这意味着它不会返回已反转的列表,它会就地修改列表,也就是说,它会反转列表,但不会返回任何内容。在Python中,任何没有显式返回值的方法都返回
None
,因此这一行:
newcontent=content.reverse()
将反转
content
,但将
newcontent
设置为
None
。您可以按相反的顺序读取任何文件,但是,如果您的文件很大,这没有意义@SivaCn:GNUCoreutils中有一个
tac
命令正是这样做的。BSD
tail
命令支持
-r
选项。请注意,Python3上可能有原始输入函数,而不是完整文件名的输入函数。在Python3上,
input
类似于
raw\u input
;你可能想添加一条评论来说明这一点。哦,是的,严格来说,这就是他/她使用python3的方式;打印功能在2.6中作为将来的导入提供:
from\uuuuu future\uuuu导入打印功能
import os.path
try:
  file1=raw_input("Enter input file: ") #raw input for python 2.X or input for python3 should work
  infile=open(file1,"r").readlines() #read file as list
  file2=raw_input("Enter output file: ")
  while os.path.isfile(file2):
    file2=raw_input("File Exists! Enter new name for output file: ")
  ofile=open(file2, "w")
  ofile.writelines(infile[::-1])#infile is a list, this will reverse it
  ofile.close()
except IOError:
  print("Error")