<p>在命令行中,<code>*</code>是一个shell通配符,shell将其展开并将文件列表传递给脚本,例如</p>
<pre><code>python txt.py "/home/Documents/1.txt" "/home/Documents/2.txt" "/home/Documents/3.txt"
</code></pre>
<p>只看第一个参数,所以只打印一个文件。你知道吗</p>
<p>您需要在shell中转义*以便它作为带星号的单个参数传递给Python。在bash shell中,可能:</p>
<pre><code>python txt.py "/home/Documents/\*.txt"
</code></pre>
<p><strong>编辑</strong>:您也可以选择命令行上的目录路径,并在程序中添加<code>*.txt</code>部分,例如</p>
<pre><code>def printAll(path):
path = path + "/*.txt"
for txtFile in glob.glob(path):
print txtFile
printAll(sys.argv[1])
call it with:
$ python txt.py "/home/Documents"
</code></pre>
<p><strong>编辑2</strong>:在路径中传递一个示例文件,脚本可以找到具有相同文件扩展名的文件,怎么样?它甚至不必存在。听起来很有趣:</p>
<pre><code>import os, sys
def printAll(path, fileext):
query = os.path.join(path, '*.' + fileext)
for someFile in glob.glob(query):
print someFile
printAll(sys.argv[1], sys.argv[2])
call it with
$ python txt.py /home/Documents txt
</code></pre>
<p>你知道吗(操作系统路径连接是一个实用程序,可以添加/如果需要的话)</p>
<p>或者在路径中传递一个示例文件,这样脚本就可以找到具有相同文件扩展名的文件了?它甚至不必存在。听起来很有趣:</p>
<pre><code>import os, sys
def printAll(path):
searchdir, filename = os.path.split(path)
tmp, fileext = os.path.splitext(filename)
path = os.path.join(searchdir, '*'.fileext)
for someFile in glob.glob(path):
print someFile
printAll(sys.argv[1])
call it with:
$ python txt.py "/home/Documents/example.txt"
</code></pre>