Search code examples
pythontext-parsing

python-reading a text file


I have a ".txt" file from which I was parsing and printing lines by two different ways, but instead of getting two outputs, I am only getting a single output of printed lines.

**pi_digits.txt contains**:--
3.141692653
  897932384
  264338327

Below is the code:

with open("pi_digits.txt") as file_object:
    #contents = file_object.read()
    #print(contents)
    for line in file_object:
        print(line.rstrip()) #deletes the whitespace of \n at the end of every string of file_object
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())`

output is only:

**
3.141692653
  897932384
  264338327
**

occurring 1 time but I think it should occur two times.


Solution

  • No, it will not occur twice. By the time you get to the end of your first loop:

        for line in file_object:
            print(line.rstrip()) #deletes the whitespace of \n at the end of every string of file_object
    

    You have read through the whole file. The file_object is positioned at the end of the file. Thus, this line reads nothing:

        lines = file_object.readlines()
    

    If you really want to go through it twice, do the readlines call first, and have both for loops use the list instead of the file iterator.