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

查看:25
本文介绍了将带有通配符的参数传递给 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 的 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天全站免登陆