我已将文件加载到列表中
line_storage = [];
try:
with open(file_name_and_path, 'r') as f:
for line in f:
line_storage.append(line) # store in list
但是当尝试将其转换为字符串(“stringify”)时:
total_number_of_lines = len(line_storage)
lineBuffer = "";
for line_index in xrange(0, total_number_of_lines):
lineBuffer += line_storage[line_index].rstrip('\n') # append line after removing newline
打印件没有显示完整内容,只显示最后一行。虽然,len(lineBuffer)是正确的。
文件内容是:
....
[04.01] Test 1:
You should be able to read this.
[04.02] Test 2:
....
=========================================================== EOF
我该如何解决这个问题?
答案 0 :(得分:2)
您的文字行可能以\r\n
结尾,而不只是\n
。删除\n
后,您将离开每行末尾的\r
。当您将其打印到终端时,每一行都将覆盖前一行,因为\r
仅将光标移回当前行的开头。
解决方案可能是使用.rstrip('\r\n')
。