【发布时间】:2014-12-30 18:53:10
【问题描述】:
我正在尝试将 Python 3 中文本文件中的行反转并写入输出文件。目前,我遇到了 infile 的最后一行在行尾不包含 \n 的问题。我从这段代码中得到了一个 TypeError 。
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] 不是更容易吗?文件的最后一行也不需要换行符。
-
.reverse 反转列表。我在一个计算 101 课上,我们还没有学过 [::1],所以我对使用它感到不舒服,因为我们必须能够解释为什么我们的代码有效。在这种情况下,最后一行确实需要一个换行符,因为它稍后将成为第一行。
标签: python file python-3.x reverse