file pointer array

F

FSH

Hello,

I have a simple question. I wish to generate an array of file
pointers. For example, I have files:

data1.txt
data2.txt
data3.txt
.....

I wish to generate fine pointer array so that I can read the files at
the same time.

for index in range(N):
fid[index] = open('data%d.txt' % index,'r')

I look forward to your advice for this problem.

-FSH
 
S

Steven D'Aprano

Hello,

I have a simple question. I wish to generate an array of file pointers.
For example, I have files:

data1.txt
data2.txt
data3.txt
....

I wish to generate fine pointer array so that I can read the files at
the same time.

for index in range(N):
fid[index] = open('data%d.txt' % index,'r')


See the fileinput module:

http://docs.python.org/library/fileinput.html


If you prefer to manage it yourself, you can do something like this:


fid = [open('data%d.txt' % index, 'r') for index in range(1, N+1)]

# Process the files.
for fp in fid:
print fp.read()

# Don't forget to close them when done.
for fp in fid:
fp.close()



You can let the files be closed by the garbage collector, but there is no
guarantee that this will happen in a timely manner. Best practice is to
close them manually once you are done.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,588
Members
45,100
Latest member
MelodeeFaj
Top