在python上按顺序读取文件

时间:2013-11-06 03:55:28

标签: 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()

我是否正确使用此代码?我似乎无法找到一个方法来反转输出文件的输入文件中的行。

输入ex。

cat dog house animal

plant rose tiger tree

zebra fall winter donkey

输出ex。

zebra fall winter donkey

plant rose tiger tree

cat dog house animal

2 个答案:

答案 0 :(得分:1)

以相反的顺序循环通过线条。这有几种方法。

使用range

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)

答案 1 :(得分:0)

这应该有效

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")