我正在編寫一個python腳本,它將讀取文件擴展名,MIME類型和文件簽名,以便我可以確定這些文件是否缺失或損壞,並確定文件類型給定的目錄。使用Python讀取MIME類型時出錯
到目前爲止我有:
import magic, os
def get_ext(dirPath):
foldercount = 0
filecount = 0
while True:
if os.path.exists(dirPath):
break
else:
print "Directory doesn't exist!"
continue
includePath = raw_input("Do you want to include the complete path to the files in the output?: Y/N\n")
if includePath.upper() == "Y":
for rootfolder, subfolders, files in os.walk(dirPath):
foldercount += len(subfolders)
filecount += len(files)
for f in files:
name = f
path = os.path.join(rootfolder, f)
ext = os.path.splitext(f)[1]
if ext != "":
print "Filename: " + str(path) + "\t\tExtension: " + str(ext) + "\tMIME: "
else:
print "Filename: " + str(path) + "\t\tExtension: no extension found"
print "Found {0} files in {1} folders".format(filecount, foldercount)
elif includePath.upper() == "N":
for rootfolder, subfolders, files in os.walk(dirPath):
foldercount += len(subfolders)
for f in files:
name = f
path = os.path.join(rootfolder, f)
ext = os.path.splitext(f)[1]
if ext != "":
print "Filename: " + str(name) + "\t\tExtension: " + str(ext)
else:
print "Filename: " + str(name) + "\t\tExtension: no extension found"
print "Found in {0} folders".format(foldercount)
else:
print "Wrong input, try again"
def getMagic(dirPath):
while True:
if os.path.exists(dirPath):
break
else:
print "Directory doesn't exist!"
continue
for rootfolder, subfolders, files in os.walk(dirPath):
for f in files:
bestand = f
mymagic = magic.Magic(mime=True)
mytype = mymagic.from_file(bestand)
print mytype
print ("The MIME type of the file %s is %s" %(bestand, mytype))
dirPath = raw_input("Directory to check files in: ")
get_ext(dirPath)
getMagic(dirPath)
get_ext()的作品,因爲它應該給我一個文件名和擴展名。 然而,當我嘗試獲取MIME類型它在某種程度上引發以下錯誤:
Traceback (most recent call last):
File "/home/nick/workspace/Proto/asdfasdf.py", line 80, in <module>
getMagic(dirPath)
File "/home/nick/workspace/Proto/asdfasdf.py", line 74, in getMagic
mytype = mymagic.from_file(bestand)
File "/usr/local/lib/python2.7/dist-packages/magic.py", line 75, in from_file
raise IOError("File does not exist: " + filename)
IOError: File does not exist: 2
我知道一個事實,即文件「2」確實存在,是一個純文本文件。 它確實給了我MIME,如果我硬編碼腳本中的文件的路徑,但我希望腳本遍歷一個目錄給我所有文件的啞劇。
有人可以解釋爲什麼它會拋出這個錯誤以及如何解決這個問題? 我使用使用PIP安裝python-魔法
感謝
將bestand = os.join(rootfolder,f)改爲os.path.join。 否則它工作得很好,謝謝! – Nick