First and foremost, I am recently new to Unix and I have tried to find a solution to my question online, but I could not find a solution.
So I am running Python
through my Unix terminal, and I have a program that parses xml
files and inputs the results into a .dat
file.
My program works, but I have to input every single xml
file (which number over 50
) individually.
For example:
clamshell: python3 my_parser2.py 'items-0.xml' 'items-1.xml' 'items-2.xml' 'items-3.xml' .....`
So I was wondering if it is possible to read from the directory, which contains all of my files into my program? Rather than typing all the xml
file names individually and running the program that way.
Any help on this is greatly appreciated.
python3 my_parser2.py *.xml
应该可以工作。
The shell itself can expand wildcards so, if you don't care about the order of the input files, just use:
python3 my_parser2.py items-*.xml
If the numeric order is important (you want 0..9
, 10-99
and so on in that order, you may have to adjust the wildcard arguments slightly to guarantee this, such as with:
python3 my_parser2.py items-[0-9].xml items-[1-9][0-9].xml items-[1-9][0-9][0-9].xml
Other than the command line option, you could just use glob
from within your script and bypass the need for command arguments:
import glob
filenames = glob.glob("*.xml")
This will return all .xml
files (as filenames) in the directory from which you are running the script.
Then, if needed you can simply iterate through all the files with a basic loop:
for file in filenames:
with open(file, 'r') as f:
# do stuff to f.
import glob
listOffiles = glob.glob('directory/*.xml')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.