【问题标题】:file is not empty however python outputs the file as empty in list form?文件不为空但是python以列表形式将文件输出为空?
【发布时间】:2021-01-03 13:38:12
【问题描述】:

我正在尝试以列表形式访问文件的内容,我尝试这样做并且文件返回为空,它不会重新识别断线并且文件肯定不是空的,谁能解释一下...

   with  open("scores.txt","a+") as filescores: 

        scores=list(filescores)
        print(scores)

输出: []

谢谢!

【问题讨论】:

  • filescores 的使用很好。默认情况下,它将是行列表。你可以使用这些函数来指定你想要的。
  • @Moinuddin 副本似乎方向错误;正如当前答案所暗示的,这里的问题是文件模式。 list(filehandle) 确实会遍历 filehandle 并将行读入列表。
  • @nagyl list(file scores) 将是惯用的方法,文件对象是行上的迭代器。 readlines 是化石

标签: python list file


【解决方案1】:

仔细查看open 函数。

r读取文件,请使用open("scores.txt","r")a 用于a追加。

【讨论】:

    【解决方案2】:

    考虑a+open mode 文件已打开以进行追加,因此文件指针位于文件末尾。 + 也允许读取文件,但从哪里读取?从头到尾!

    易于演示。

    首先,创建一个文件:

    from pathlib import Path 
    
    p=Path('/tmp/file')
    
    with open(p, 'w') as f:
        f.write('\n'.join([str(e) for e in range(10)]))
        # file will be '0\n1\n2\n'...
    

    现在使用a+ 模式打开该文件:

    with open(p, 'a+') as f:
        l=list(f)
    
    >>> l
    []
    

    l 为空,因为f 在文件末尾。也很容易改变:

    with open(p, 'a+') as f:
        f.seek(0)        # reposition the file pointer to the start of file
        l=list(f)
    
    >>> l
    ['0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9']
    

    或者,只需将r 用于读取模式,文件指针将位于文件的开头:

    with open(p, 'r') as f:
        l=list(f)
    # ['0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9']
    

    【讨论】:

      猜你喜欢
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多