gpt4 book ai didi

python - 文件名中的空格 python 3.4.2

转载 作者:行者123 更新时间:2023-12-01 03:08:55 25 4
gpt4 key购买 nike

我创建了这个小程序来搜索目录中的所有 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

最佳答案

os.system() 使用 shell 来执行您的命令。您必须引用您的文件名,shell 才能将空格识别为文件的一部分,您可以使用 shlex.quote() function 来执行此操作:

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

但是,根本没有理由使用 os.system() 和 shell。您应该使用 subprocess.run() 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)。

关于python - 文件名中的空格 python 3.4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com