Python 如何从外部驱动器获取文件元数据?

How to get file metadata from external drive in Python?

我编写了一个 Python 脚本,用于从文件目录中收集文件元数据(文件名、创建日期、创建时间、上次修改数据、上次修改时间)。但是,当目录是位于外部硬盘驱动器中的路径时,脚本不起作用。我不知道为什么。

代码如下:

import os
from os.path import basename
import datetime
import time
def getSize(filename):
    st = os.stat(filename)
    print st
    return st.st_size

#get last modified date
def getMTime(filename):
    fileModTime = os.path.getmtime(filename)
    return fileModTime

#get creation date
def getCTime(filename):
    fileModTime = os.path.getctime(filename)
    return fileModTime

#get data from directory

MyDirectory = "H:[=11=]_tempfiles0115_Portfolio\Work\Work\BarBackUp"
MyExtension = ".jpg"

#write to file
WorkingDirectory = "C:\Users\Admin\Downloads\demo\"
MyTxtFile = WorkingDirectory + "fileData6.txt"

delim = ";"

with open(MyTxtFile, 'wb') as f:
  f.write(delim.join(["FILENAME", "FILESIZE", "mDATE","mTIME",
                      "cDATE","cTIME"]) + "\n")

for root, dirs, files in os.walk(MyDirectory):
    for file in files:
        if file.endswith(MyExtension):
            #get File Name
            a = (os.path.join(root, file))
            #print a
            filename = a
            MyFileName = basename(a)

            #get File Size
            MyFileSize = getSize(filename) / 1000
            print MyFileName + " >>> file size: " + str(MyFileSize) + "Kb"

            #get modification time V2
            modTimeV2 = getMTime(filename)
            modTimeV2 = time.strftime("%Y/%d/%m;%I:%M:%S   %p", \
                                      time.localtime(modTimeV2))
            print "time modified: " + str(modTimeV2)

            #get creation time 
            creTime = getCTime(filename)
            creTime = time.strftime("%Y/%d/%m;%I:%M:%S %p", \
                                    time.localtime(creTime))
            print "time created: " + str(creTime) 

            #--------
            #write data to file
            entry = delim.join([str(MyFileName), str(MyFileSize), \
                                str(modTimeV2), str(creTime)]) + "\n"
            f.write(entry)

   print "<<<<<<everything went fine>>>>>>"

你的代码对我来说工作正常。您的 "MyDirectory" 变量中包含转义字符。尝试在引号前添加一个 r:

MyDirectory = r"H:[=10=]_tempfiles0115_Portfolio\Work\Work\BarBackUp"

MyDirectory = "H:/0_tempfiles/150115_Portfolio/Work/Work/BarBackUp"

MyDirectory = "H:\0_tempfiles\150115_Portfolio\Work\Work\BarBackUp"