Kandan Siva
Kandan Siva

Reputation: 479

How to copy file object in python

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

Upvotes: 0

Views: 2288

Answers (1)

Rakesh
Rakesh

Reputation: 82815

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)

Upvotes: 1

Related Questions