我有一个脚本,我想使用它来枚举文件夹中的所有文件类型:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import argparse
import magic
import os
# Argparse starts here
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None)
args = parser.parse_args()
for files in args.input:
if magic.from_file(files,mime=True) == "text/plain":
print (files, "=" , magic.from_file(files,mime=True) )
当我输入文件时它工作得很好:
即使我输入两个文件:
但不是当我输入所有文件时:
错误说:
Traceback (most recent call last):
File "Test.py", line 15, in <module>
if magic.from_file(files,mime=True) == "text/plain":
File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 135, in from_file
return m.from_file(filename)
File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 85, in from_file
with open(filename):
OSError: [Errno 22] Invalid argument: '*.txt'
但这*.txt
正是我想要输入的;我也想输入任何文件*.*
这是与python-magic
我输入文件的方式有关还是由其引起的问题?
如果你想使用 * 之类的东西,那么你必须“glob”这些文件。这可能会令人困惑,因为 globbing 可能发生在许多地方。我不熟悉您使用的 shell,但是如果您使用的是 bash,那么 bash 会在将 glob传递给 Python之前执行它。换句话说,如果 *.txt 实际上匹配某些内容,bash 会用文件列表替换它,然后将该列表传递给 Python(作为单独的参数)。然后你的工作就是在 Python 中处理任意数量的参数(可能使用 argparse)。如果 *.txt 不匹配任何内容,则它不会被扩展,Python 会看到 *.txt,您必须将其作为错误处理。
在这里,看起来 globbing 没有发生,这意味着您的 shell 没有匹配的内容,或者您的 shell 没有进行 globbing。如果它不进行通配,那么您可以使用glob模块在 Python 中进行通配。不过,通常 globbing 是由 shell 完成的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句