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中添加的)
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)
这是您的程序的重写。我这样做了:
getListofFiles()返回成为元组列表。每一项都包含三个要素;文件名、大小和时间戳,这似乎是所谓的纪元时间(自 1970 年以来以秒为单位的时间;您必须浏览有关日期和时间的 Python 文档)。重写的代码:
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)