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

时间:2015-04-06 21:45:46

标签: python directory metadata filenames

我编写了一个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:\0_tempfiles\150115_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>>>>>>"

1 个答案:

答案 0 :(得分:1)

您的代码适用于我。你的&#34; MyDirectory&#34;变量中包含转义字符。尝试在引号前面添加一个r:

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

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

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