【问题标题】:Python: OSError: [Errno 22] Invalid argument: '*.txt'Python:OSError:[Errno 22] 无效参数:'*.txt'
【发布时间】:2018-05-18 23:11:39
【问题描述】:

我想使用一个脚本来枚举文件夹中的所有文件类型:

#!/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) )

当我输入文件时效果很好:

即使我输入了两个文件:

但不是当我输入 ALL 文件时:

错误提示:

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 相关的问题还是由我输入文件的方式引起的?

【问题讨论】:

  • 试图打开一个名为*.txt 的文件是没有意义的。你想循环每个文件吗?您必须为此执行多次打开。

标签: python parameter-passing command-line-arguments argparse python-magic


【解决方案1】:

如果你想使用 * 之类的东西,那么你必须“glob”这些文件。这可能会令人困惑,因为通配可能发生在许多地方。我不熟悉您使用的 shell,但如果您使用的是 bash,那么 bash 会在它被传递给 Python 之前执行 glob before。换句话说,如果 *.txt 确实匹配某些内容,bash 将其替换为文件列表,然后将该列表传递给 Python(作为单独的参数)。然后你的工作就是在 Python 中处理任意数量的参数(可能使用 argparse)。如果 *.txt 不匹配任何内容,则它不会被扩展并且 Python 会看到 *.txt,您必须将其视为错误。

这里看起来没有发生 globbing,这要么意味着你的 shell 没有匹配的东西,要么你的 shell 不做 globbing。如果它不进行 globbing,那么您可以使用 glob 模块在 Python 中进行 globbing。不过,通配符通常是由 shell 完成的。

【讨论】:

  • 谢谢,解决方案是在 Windows 10 上使用 bash,因为 CMD 无法处理此问题
【解决方案2】:

试图打开一个名为*.txt 的文件是没有意义的。 open 不支持使用通配符打开多个文件。

如果你想在每个文件上循环,你必须为此执行多次打开,使用glob.glob 来返回匹配的文件名

import glob
for fexp in glob.glob(filename):
    with open(fexp) as f:
      # do something with the opened file
      pass

注意,如果目录错误,glob.glob 返回一个空列表。

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多