开发者

Dynamic filenames

开发者 https://www.devze.com 2023-01-11 19:35 出处:网络
So I\'m working on a program where I store data into multiple .txt files. The naming convention I want to use is file\"xx\" where the Xs are numbers, s开发者_如何转开发o file00, file01, ... all the wa

So I'm working on a program where I store data into multiple .txt files. The naming convention I want to use is file"xx" where the Xs are numbers, s开发者_如何转开发o file00, file01, ... all the way up to file20, and I want the variables assigned to them to be fxx (f00, f01, ...).

How would I access these files in Python using a for loop (or anther method), so I don't have to type out open("fileXX") 21 times?


The names are regular. You can create the list of filenames with a simple list comprehension.

["f%02d"%x for x in range(1,21)]


An example of writing t to all files:

for x in range(22): #Remember that the range function returns integers up to 22-1
    exec "f%02d = open('file%02d.txt', 'w')" % (x, x)

I use the exec statement but there's probably a better way. I hope you get the idea though.

NOTE: This method will give you the variable names fXX to work with later if needed. The last two lines are just examples. Not really needed if all you need is to assign fileXX.txt to fXX.

EDIT: Removed the other last two lines because it seemed that people just weren't too happy with me putting them there. Explanations for downvotes are always nice.


Look into python's glob module.

It uses the usual shell wildcard syntax, so ?? would match any two characters, while * would match anything. You could use either f??.txt or f*.txt, but the former is a more strict match, and wouldn't match something like fact_or_fiction.txt while the latter would.

E.g.:

import glob
for filename in glob.iglob('f??.txt'):
    infile = file(filename)
    # Do stuff...


I think the point is the OP wants to register the variables programagically:

for i in range( 20 ):
    locals()[ "f%02d" % i ] = open( "file%02d.txt" % i )

and then e.g.

print( f01 )
...


files = [open("file%02d", "w") for x in xrange(0, 20+1)]
# now use files[0] to files[20], or loop

# example: write number to each file
for n, f in enumerate(files):
  files.write("%d\n" % n)

# reopen for next example
files = [open("file%02d", "r") for x in xrange(0, 20+1)]
# example: print first line of each file
for n, f in enumerate(files):
  print "%d: %s" % (n, f.readline())
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号