问题
i have this function: write_reversed_file(input_filename, output_filename)
that writes to the given output file the contents of the given input file with the lines in reversed order. i just need the output to be written to the file (output_filename
) rather than to the terminal (python shell).
the only part im missing is to store the output into the file. i successfully managed to complete the reversing lines part.
def write_reversed_file(input_filename, output_filename):
for line in reversed(list(open(filename))):
print(line.rstrip())
回答1:
def write_reversed_file(input_filename, output_filename):
s = ""
f = open(input_filename,"r")
lines = f.read().split("\n")
f.close()
for line in reversed(lines):
s+=line.rstrip()+"\n"
f = open(outPutFile.txt,"w")
f.write(s)
f.close()
回答2:
It is good practice to use 'with open as' format when working with files since it is automatically closing the file for us. (as recommended in docs.python.org)
def write_reversed_file(input_filename, output_filename):
with open(output_filename, 'w') as f:
with open(input_filename, 'r') as r:
for line in reversed(list(r.read())):
f.write(line)
write_reversed_file("inputfile.txt", "outputfile.txt")
来源:https://stackoverflow.com/questions/29586063/storing-data-into-a-file-rather-than-returning-to-the-terminal