【问题标题】:cannot print what i read from file python无法打印我从文件 python 中读取的内容
【发布时间】:2020-11-08 06:42:36
【问题描述】:

好的。所以我写了一个程序,从阅读器对象中读取每一行。

with open(r'C:\Users\Jayesh B\Documents\Programming\Python\Practicals\Program5\program5.txt','r') as target:
    lines = target.readlines()
    newfllines = []
    for line in lines:
        if line[0].lower() == 'a':
            newfllines.append(line)
    print(lines)
    a = target.read()
    print(a)

我的文件不是空的,因为打印行给了我输出

['aaditya\n', 'aaaaaaab\n', 'efsgrbdb\n', 'grr\n', 'gegeb\n', 'ee\n', 'adi \n', 'test123\n', 'sb\n', 'fsbr\n', 'bfs\n', 'brsbwb\n', 'wb\n', 'wbwb\n', 'wbe']

但是第二个打印语句没有给出任何输出。谁能告诉我做错了什么? 请注意..我使用的是python版本:3.8.6

Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32

【问题讨论】:

  • 您应该在第二个read 调用之前添加target.seek(0)。这是改变文件对象的位置。因为在第一次readlines 调用之后,文件位置将在文件末尾。
  • target.readlines()之后,你已经到达文件末尾,所以下一次读取什么都没有。
  • 好的,谢谢它的工作,我不得不寻找它

标签: python python-3.x readlines


【解决方案1】:

一旦你到达流的末尾,你需要再次重新读取文件(你不需要关闭文件,因为你正在使用with)并修复错误的缩进:

with open(r'C:\Users\Jayesh B\Documents\Programming\Python\Practicals\Program5\program5.txt','r') as target:
  lines = target.readlines()
  newfllines = []
  for line in lines:
    if line[0].lower() == 'a':
      newfllines.append(line)
print(lines)
a = open(r'C:\Users\Jayesh B\Documents\Programming\Python\Practicals\Program5\program5.txt','r').read()
print(a)

你也可以使用target.seek(0)再次回到顶部

【讨论】:

  • 我修复了缩进,但它仍然不起作用。但正如你建议再次打开文件它工作。现在结束问题谢谢。
【解决方案2】:

当你使用target.readlines()方法时,指针会遍历整个文件并在末尾,所以当你调用taeget.read()方法时,因为指针在文件末尾,所以没有什么可以读取的.您可以通过在target.readlines() 之后使用target.seek(0) 方法来解决此问题,因为它将重置您的指针并将其带到文件中的第一个字符。此外,请确保缩进正确,所有内容都应在 with 代码块中,因为一旦您从该代码块中取消缩进,文件就会关闭。

【讨论】:

    【解决方案3】:
    with open(r'program.txt','r') as target:
        lines = target.readlines()
        newfllines = []
        for line in lines:
            if line[0].lower() == 'a':
                newfllines.append(line)
        print(lines)
        target.seek(0)
        a = target.read()
        print(a)
        print(newfllines)
    

    输出

    ['ciao\n', 'come\n', 'stai\n', 'a\n', 'a\n', 'a']
    ciao
    come
    stai
    a
    a
    a
    ['a\n', 'a\n', 'a']
    

    【讨论】:

      【解决方案4】:

      您正在尝试读取已关闭的文件。你可以试试这个。

      with open(r'C:\Users\Jayesh B\Documents\Programming\Python\Practicals\Program5\program5.txt','r') as target:
              lines = target.readlines()
      newfllines = []
      for line in lines:
          if line[0].lower() == 'a':
              newfllines.append(line)
      print(lines)
      with open(r'C:\Users\Jayesh B\Documents\Programming\Python\Practicals\Program5\program5.txt','r') as target:
          a = target.read()
      print(a)
      

      【讨论】:

        猜你喜欢
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 2017-08-06
        相关资源
        最近更新 更多