我正在嘗試使Python 3中的文本文件中的行反轉並寫入outfile。目前,我在最後一行infile中沒有包含\ n的問題。我從這段代碼中得到一個TypeError。從文件中翻轉行Python 3
def main():
endofprogram = False
try:
inputfile = input("Enter name of input file: ")
ifile = open(inputfile, "r", encoding="utf-8")
outputfile = input("Enter name of output file: ")
while os.path.isfile(outputfile):
if True:
outputfile = input("File Exists. Enter name again: ")
ofile = open(outputfile, "w")
except IOError:
print("Error opening file - End of program")
endofprogram = True
#If there is not exception, start reading the input file
if endofprogram == False:
newline = "\n"
for line in ifile:
line = line.strip
line = line + "\n"
lines = ifile.readlines()
lines.reverse()
newlines= "".join(lines)
print(newlines)
ifile.close()
ofile.close()
main() # Call the main to execute the solution
究竟是什麼「.reverse」?使用reverse = lines [:: - 1]會不會更容易?該文件的最後一行也不需要換行符。 – 2014-11-04 00:28:56
.reverse反轉列表。我在一個計算機101課上,我們還沒有學會[:: 1],所以我不習慣使用它,因爲我們必須能夠解釋爲什麼我們的代碼有效。這種情況下的最後一行確實需要一個新的行字符,因爲它稍後將成爲第一行。 – 2014-11-04 00:34:39