Goga Goga - 12 days ago 7
Python Question

How to read files from directory by name?

I need to read files in directory by name using interval

0-400
.
It means that programm reads files with names from 0 to 400.

Now I have this code:

with open(file) as xml:
doc = xmltodict.parse(xml.read())


So, I tried:

for num in range(0,400)
filename = num".vtb"
doc = xmltodict.parse(filename.read())


Problem is that I use:

if __name__ == '__main__':
files = glob.glob("data*")
pool = Pool()
pool.map(open_xml, files)
c.close()


I pass array
files
to
map
function. How can I pass
0-400
array files instead that?

Answer

Not sure of what you're asking. But the code you tried to write does not work, and I presume you want to know how to make it work. So, you wrote:

for num in range(0,400)
  filename = num".vtb"
  doc = xmltodict.parse(filename.read())

Instead, try:

for num in range(0,400)
  filename = str(num) + ".vtb"
  doc = xmltodict.parse(filename.read())

If this does not do what you want, then your problem lies elsewhere.

EDIT

Reading your comment, what I understand is that you want to pass these 0 to 400 files to map. Then you just need to build a list containing all the paths to use:

filenames = []
for num in range(0,400)
    filenames.append(str(num) + ".vtb")

Then:

pool.map(open_xml, filenames)
Comments