Reputation: 79
Basically I am trying to open multiple files according to name of the list pass. I have files in Log/ with following name
here is the dir structure
script---myfile.py
|
|----Log/*.txt
following files are in Log/
parse_1d_30a.txt,
parse_10d_60a.txt,
parse_20d_90a.txt
#!/usr/bin/python
deviation = ['1', '10', '20']
angle = ['30', '60', '90']
def openFile(dev, ang):
p = open('Log/parse_%sd_%sa.txt'%(dev, ang), 'r')
print "open file is", p.name
p.close()
print "file closed."
def main():
for d, a in zip(deviation, angle):
openFile(d, a)
main()
So, when I execute the code first file parse_1d_30a.txt opens but for other files it gives IOError: no such file or directory.
I think by using 'glob' it might work. I know how to open the files individually in python but not sure why I am wrong with above code and what is the alternative for the same.
Thanks
Upvotes: 2
Views: 2847
Reputation: 41987
With glob
you can not impose absolute preciseness like Regex. In glob, you need to use one of *
(any number of characters) or ?
(any single character), which makes it difficult to do strict matching.
The close i can get:
>>> import glob
>>> glob.glob(r'parse_[0-9]*d_[0-9][0-9]a.txt')
['parse_20d_90a.txt', 'parse_1d_30a.txt', 'parse_10d_60a.txt']
Here *
can match any number of characters which might lead to wrong output based on the file names and your desired output.
Upvotes: 1