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 に答える