在Python中获取文件大小、创建日期和修改日期

Nir*_*ira 6 python size file list info

我需要获取文件信息(路径、大小、日期等)并将其保存在 txt 中,但我不知道在哪里或如何执行此操作。

这就是我所拥有的:

ruta = "FolderPath"
os.listdir(path=ruta)
miArchivo = open("TxtPath","w")
def getListOfFiles(ruta):
 listOfFile = os.listdir(ruta)
 allFiles = list()
 for entry in listOfFile:
  fullPath = os.path.join(ruta, entry)
  if os.path.isdir(fullPath):
   allFiles = allFiles + getListOfFiles(fullPath)
  else:
   allFiles.append(fullPath)
 return allFiles

listOfFiles = getListOfFiles(ruta)
for elem in listOfFiles:
 print(elem)
 print("\n")
 miArchivo.write("%s\n" % (elem))
miArchivo.close()
Run Code Online (Sandbox Code Playgroud)

输出是(只有路径,没有其他信息): 在此输入图像描述

我想要的是:V:\1111111\222222222\333333333\444444444\5555555555\66666666\Folder\文件名--大小--修改日期等等

Yam*_*mar 11

我认为您可能想使用scandir而不是listdir为此:

for item in os.scandir(my_path):
     print(item.name, item.path, item.stat().st_size, item.stat().st_atime)
Run Code Online (Sandbox Code Playgroud)

您还需要在此处查看有关相应呼叫的更多详细信息(您正在寻找的时间和规模)。(os.scandir是在python 3.6中添加的)


lea*_*arn 5

https://docs.python.org/2.7/library/os.path.html#module-os.path

os.path.getsize(path) # size in bytes
os.path.ctime(path) # time of last metadata change; it's a bit OS specific.
Run Code Online (Sandbox Code Playgroud)

这是您的程序的重写。我这样做了:

  1. 使用 autopep8 重新格式化以获得更好的可读性。(您可以安装它来美化您的代码。但是,除了帮助您完成代码完成和 GUI 调试器之外,PyCharm Community Edition 等 IDE 也可以帮助您完成相同的任务。)
  2. 让您的getListofFiles()返回成为元组列表。每一项都包含三个要素;文件名、大小和时间戳,这似乎是所谓的纪元时间(自 1970 年以来以秒为单位的时间;您必须浏览有关日期和时间的 Python 文档)。
  3. 元组以 .csv 样式格式写入文本文件(但请注意,有模块可以以更好的方式执行相同操作)。

重写的代码:

import os

def getListOfFiles(ruta):
    listOfFile = os.listdir(ruta)
    allFiles = list()
    for entry in listOfFile:
        fullPath = os.path.join(ruta, entry)
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            print('getting size of fullPath: ' + fullPath)
            size = os.path.getsize(fullPath)
            ctime = os.path.getctime(fullPath)
            item = (fullPath, size, ctime)
            allFiles.append(item)
    return allFiles

ruta = "FolderPath"
miArchivo = open("TxtPath", "w")
listOfFiles = getListOfFiles(ruta)
for elem in listOfFiles:
    miArchivo.write("%s,%s,%s\n" % (elem[0], elem[1], elem[2]))
miArchivo.close()
Run Code Online (Sandbox Code Playgroud)

现在它做到了这一点。

my-MBP:verynew macbookuser$ python verynew.py; cat TxtPath
getting size of fullPath: FolderPath/dir2/file2
getting size of fullPath: FolderPath/dir2/file1
getting size of fullPath: FolderPath/dir1/file1
FolderPath/dir2/file2,3,1583242888.4
FolderPath/dir2/file1,1,1583242490.17
FolderPath/dir1/file1,1,1583242490.17
my-MBP:verynew macbookuser$
Run Code Online (Sandbox Code Playgroud)