0

I am opening a file in python using with command as given below. Then I am copying the object to w.

import os

os.chdir(r"C:\Users\")

with open(r"abc.040", 'r+') as k:
    w = k

for a in w:
    print(a)

But when I try to iterate w object through for loop, I am getting below error.

Traceback (most recent call last):
  File "C:/Users/w.py", line 8, in <module>
    for a in w:
ValueError: I/O operation on closed file.

How to copy a file instance

8
  • 2
    The error itself is self explanatory. Commented Aug 7, 2018 at 7:26
  • Is the indentation the same as you're showing here? Commented Aug 7, 2018 at 7:27
  • 2
    Unlike some other languages Python creates references by = and no copies. So you are still using the same object just under a new name. Commented Aug 7, 2018 at 7:31
  • 1
    When you open a file in a with block, the file gets automatically closed when you exit the block. k (and w, they are just two names for the same file object) is closed when you reach the for loop. Commented Aug 7, 2018 at 7:32
  • 1
    w = k is not a copy. Commented Aug 7, 2018 at 7:59

1 Answer 1

1

Use readlines

Ex:

import os

os.chdir(r"C:\Users")
with open(r"abc.040", 'r+') as k:
    w = k.readlines()

for a in w:
    print(a)
Sign up to request clarification or add additional context in comments.

2 Comments

Is it not possible to copy the object and use it. Something like deepcopy
file content is copied to w using 'readlines' for you to reuse.

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.