Python没有打印正确的结果,尽管结果是

2024-04-16 18:45:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我已将一个文件加载到列表中

    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

我怎样才能解决这个问题


Tags: 文件ofintestnumber列表forindex
1条回答
网友
1楼 · 发布于 2024-04-16 18:45:54

您的文本行可能以\r\n结尾,而不仅仅是\n。通过删除\n,您将\r留在每行的末尾。当您将此打印到终端时,每行都将覆盖前一行,因为\r只会将光标移回当前行的开头

解决方法可能是使用.rstrip('\r\n')

相关问题 更多 >