2
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
4

2 回答 2

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)
于 2013-11-06T04:04:18.173 回答
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")
于 2013-11-06T04:35:06.473 回答