Search code examples
pythonpython-3.xreadlines

cannot print what i read from file python


Ok. so I wrote a program that reads each line from a reader object.

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)

My file is not empty as printing lines gives me the output

['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']

but the second print statement does not give any output. Can anyone tell what i am doing wrong? Please note.. I am using the python version : 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

Solution

  • Once you have reached end of the stream, you need to re-read the file again (you don't need to close the file as you are using with) and also fix bad indentation:

    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)
    

    Also you can go to the top again using target.seek(0)