0

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 2
    could you format it a little? there should be a code insert button that looks like <>, it's hard to help debug like this – OmegaNalphA Nov 09 '21 at 18:36
  • Does this answer your question? [Iterate through a file lines in python](https://stackoverflow.com/questions/48124206/iterate-through-a-file-lines-in-python) – Luke B Nov 09 '21 at 18:40
  • alternatively, if you want to loop over lines twice, you can update the loop condition to something like `for line in lines * 2:` – rv.kvetch Nov 09 '21 at 18:41

1 Answers1

1

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • Thanks for the help man, it seems I have a weak fundamental of file parsing. – vivek upadhyay Nov 09 '21 at 19:32
  • A file always has a "current position". Every time you read, you advance the "current position". When you reach the end, it stays at the end until you close the file or use `.seek` to change the position. – Tim Roberts Nov 09 '21 at 19:44