将带有通配符的参数传递给Python脚本 [英] Passing arguments with wildcards to a Python script

查看:217
本文介绍了将带有通配符的参数传递给Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

c:\data\> python myscript.py *.csv

并将目录中的所有.csv文件传递到我的python脚本(这样sys.argv包含["file1.csv", "file2.csv"]等)

and pass all of the .csv files in the directory to my python script (such that sys.argv contains ["file1.csv", "file2.csv"], etc.)

但是sys.argv只是收到["*.csv"],指示通配符没有展开,因此这是行不通的.

But sys.argv just receives ["*.csv"] indicating that the wildcard was not expanded, so this doesn't work.

我觉得有一个简单的方法可以执行此操作,但是无法在Google上找到它.有什么想法吗?

I feel like there is a simple way to do this, but can't find it on Google. Any ideas?

推荐答案

您可以使用glob模块,这样,您就不必依赖特定shell的行为了(嗯,您仍然依赖于shell不会扩展参数,但至少可以通过转义通配符:-)来使这种情况在Unix中发生.

You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).

from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument

这篇关于将带有通配符的参数传递给Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆