Python 没有打印正确的结果,尽管结果是正确的
Python not printing the correct results, though the results is correct
我已将文件加载到列表中
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
我该如何解决这个问题?
您的文本行可能以 \r\n
结尾,而不仅仅是 \n
。通过删除 \n
,您将在每行的末尾留下 \r
。当您将其打印到终端时,每一行都会覆盖前一行,因为 \r
只会将光标移回当前行的开头。
解决方案可能是使用 .rstrip('\r\n')
。
我已将文件加载到列表中
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
我该如何解决这个问题?
您的文本行可能以 \r\n
结尾,而不仅仅是 \n
。通过删除 \n
,您将在每行的末尾留下 \r
。当您将其打印到终端时,每一行都会覆盖前一行,因为 \r
只会将光标移回当前行的开头。
解决方案可能是使用 .rstrip('\r\n')
。