Python 3.4.2文件名中的空格

2024-04-25 08:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了这个小程序来搜索一个目录中的所有PDF,确定它们是否可搜索,然后将它们移动到适当的目录。你知道吗

我是Python新手,这可能不是最好的方法,但它确实可以工作,直到文件名中有空格,并且返回以下内容。你知道吗

任何帮助都将不胜感激。你知道吗

>>> os.system("pdffonts.exe " + pdfFile + "> output.txt")
99



import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory
numFiles = len(fileDir) # Lenght of list
startFile = 0 # Counter variable
seekWord = "TrueType"
while startFile < numFiles:
    pdfFile=fileDir[startFile]
    os.system("pdffonts.exe " + pdfFile + "> output.txt")
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: shutil.move(pdfFile, "OCR")
    startFile = startFile + 1

Tags: import目录txtoutputpdfosexesystem
2条回答

问题似乎不是来自python,而是Windows shell。你需要用引号括起来。因为我没有你的程序pdffonts.exe,我无法调试。我还让你的代码更像Python

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory

seekWord = "TrueType"
for pdfFile in fileDir:
    os.system('pdffonts.exe "{0}"> output.txt'.format(pdfFile))
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: 
        shutil.move(pdfFile, "OCR")

os.system()使用shell执行命令。您必须引用您的文件名,shell才能将空格识别为文件的一部分,您可以使用^{} function

os.system("pdffonts.exe " + shlex.quote(pdfFile) + "> output.txt")

但是,根本没有理由使用os.system()和shell。您应该使用^{} function并将其配置为在不使用重定向或shell的情况下传回输出:

import subprocess

seekWord = b"TrueType"
for pdfFile in fileDir:
    result = subprocess.run(["pdffonts.exe", pdfFile], stdout=subprocess.PIPE)
    fileContent = result.stdout
    if seekWord in fileContent:
        # ...

因为pdfFile直接传递给pdffonts.exe,所以不需要担心shell解析,空格也不再重要。你知道吗

注意,我将seekWord改为bytes文字,因为result.stdout是字节值(这里不需要尝试将结果解码为Unicode)。你知道吗

相关问题 更多 >