0

I have two versions of similar code, one works, the other doesn't:

version 1

  #some code
with open('file', 'w') as f:
        f.writelines(new_lines)

with open('file') as f:
        i = 0
        for line in f:
           i = i + 1
           if i != 5 and i != 18 and i != 27:
              row.append(line)

version 2

   # some code
with open('file', 'w') as f:
        f.writelines(new_lines)
        i = 0
        for line in f:
           i = i + 1
           if i != 5 and i != 18 and i != 27:
              row.append(line)

When executing the version 2 code, I got an error which says that the file is not open. I got confused because obviously the code is still in the with statement. Does the file get closed automatically right after the f.writelines() method?

3
  • It would probably help if you included the full traceback you're getting. I suspect you're misreading the error message. Commented Oct 2, 2013 at 2:58
  • 1
    You seem to be trying to iterate/read the lines of a file you've opened for writing. Commented Oct 2, 2013 at 2:59
  • In v1 and v2, the f.writelines(new_lines) will replace the entire contents of the file with new_lines. Is this what you want? Commented Oct 2, 2013 at 3:02

2 Answers 2

2

The issue you're having has to do with the mode you're using to open the file. In the first example, you first open it for writing with the "w" mode. Then you close it a reopen it with the default "r" mode. This makes a difference!

To start with, you're not allowed to read from a file that is open with the regular "w" mode. You can use "w+" to allow both reading and writing, or "r+" if you don't want it to truncate the file immediately after you open it.

The other issue is the location you're at in the file. When you write your data to the file, you'll end up at the end of the file's data, and so just reading it from there will not get you anything. You will need to call f.seek(0) to go back to the start of the file, so you can read it again.

But, it's a bit silly to write the file and then read back the lines you just wrote (unless there's other complicated logic involved). I'd suggest making your for line in f loop be for line in new_lines instead, which avoids reading the file unnecessarily.

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

Comments

1

You're iterating over the file while it's in writing mode. Change it to with open('file', 'r+') as f:

After f.writelines(new_lines), you also need to go back to the beginning of the file in order to iterate through each line. Put f.seek(0) in before the loop

2 Comments

I think OP will also probably want to f.seek(0) as well, no?
Yep, that'd be where I would expect it.

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.