我正在尝试将Python 3中的文本文件中的行反转并写入到外部文件中。目前,我对不包含行尾\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发布于 2014-11-04 21:44:28
最后我这么做是为了让它运转..。
if endofprogram == False:
lines = ifile.readlines()
linelist = []
for line in lines:
line = line.strip("\n")
line = line + "\n"
linelist.append(line)
linelist.reverse()
newlines= "".join(linelist)
ofile.write(newlines) 发布于 2014-11-04 00:30:19
使用您的规范来完成这一任务的最简单的方法--假设我正确理解,并且您想要做的就是颠倒每一行的顺序--就是利用reverse方法来处理python中的列表。因此,对于任何给定的行:
#define line here
line_list = list(line)
line_list.reverse()
reversed_line = ''.join(line_list)编辑:根据换行符的问题,这里有一个修改:
#define line here
line_list = list(line.replace('\n', ''))
line_list.reverse()
reversed_line = ''.join(line_list) + '\n'https://stackoverflow.com/questions/26725722
复制相似问题