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.

3
  • 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 Commented Nov 9, 2021 at 18:36
  • Does this answer your question? Iterate through a file lines in python Commented Nov 9, 2021 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: Commented Nov 9, 2021 at 18:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help man, it seems I have a weak fundamental of file parsing.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.