简体   繁体   English

如何从目录中输入多个文件

[英]How to input multiple files from a directory

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. 首先,我最近刚接触Unix,我试图在线找到我的问题的解决方案,但我找不到解决方案。

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. 所以我通过我的Unix终端运行Python ,我有一个解析xml文件的程序,并将结果输入到.dat文件中。

My program works, but I have to input every single xml file (which number over 50 ) individually. 我的程序有效,但我必须单独输入每个xml文件(数量超过50 )。

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. 而不是单独键入所有xml文件名并以这种方式运行程序。

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: shell本身可以扩展通配符,因此,如果您不关心输入文件的顺序,只需使用:

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: 如果数字顺序重要(您想0..910-99等的顺序,您可能需要稍微调整通配符的参数,以保证这一点,如用:

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: 除了命令行选项之外,您可以在脚本中使用glob并绕过命令参数的需要:

import glob 
filenames = glob.glob("*.xml")

This will return all .xml files (as filenames) in the directory from which you are running the script. 这将返回运行脚本的目录中的所有.xml文件(作为文件名)。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM