python - 列出所有目录和文件 = 每个的 ctime
问题描述
所以我对一般的编码还是很陌生,最近我选择了 python 作为我的第一门编程语言。截至目前,我的目标是制作一个脚本,列出指定目录的所有文件和子目录(以及每个目录的 ctime)。我确实有那个列表,但我无法让 ctime 正常工作。如果我尝试将文件和子目录放在一个函数中,它会说它不能获取列表。出于某种原因,它确实适用于根位置。
这是我现在的代码:
def my_function():
z = os.path.getctime(root)
c = os.path.getctime(dirs)
a = os.path.getctime(files)
time = datetime.fromtimestamp(z,c,a).strftime("%Y-%m-%d %H:%M:%S {}")
print(time)
import os
from datetime import datetime
os.getcwd()
os.chdir("U:/")
x = os.access("U:/verzeichnis xyz", os.F_OK)
if x == True:
print("Access to directory xyz = ", x)
path = "U:/verzeichnis xyz"
for (root,dirs,files) in os.walk(path, topdown=True):
print(root)
print(dirs)
print(files)
my_function()
print("---------------")
else:
print("Access Denied")
输出:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\python\test3.py in <module>
25 print(dirs)
26 print(files)
---> 27 my_function()
28 print("---------------")
29 else:
~\python\test3.py in my_function()
8 def my_function():
9 z = os.path.getctime(root)
---> 10 c = os.path.getctime(dirs)
11 a = os.path.getctime(files)
12 time = datetime.fromtimestamp(z,c,a).strftime("%Y-%m-%d %H:%M:%S {}")
~\AppData\Local\Continuum\anaconda3\lib\genericpath.py in getctime(filename)
63 def getctime(filename):
64 """Return the metadata change time of a file, reported by os.stat()."""
---> 65 return os.stat(filename).st_ctime
66
67
TypeError: stat: path should be string, bytes, os.PathLike or integer, not list
PS:我在 Windows 10 Pro 上使用 python 3.7,verzeichnis xyz 是我的示例目录编辑:我将如何添加目录和文件,我的输出在上面列出
解决方案
my_function
需要根目录和来自 的文件os.walk
,然后遍历files
.
例如:
def my_function(root, files):
for file in files:
path = os.path.join(root, file)
z = os.path.getctime(path)
time = datetime.fromtimestamp(z).strftime("%Y-%m-%d %H:%M:%S")
print("Timestamp of '%s' is %s" % (file, time))
推荐阅读
- tensorflow.js - 如何在 TFJS hub 模型上使用 Model.save 功能?
- java - 如何使用 Around 方面包装所有存储库调用
- azure-devops-server - 在 Azure DevOps 服务器(TFS on Prem)中,有没有办法将变更集直接链接到超链接?
- c - 我该如何处理这个分段错误
- struct - 消除方法中的双重可变借用
- c++ - 反汇编 Visual Studio
- r - 在不同的列中绘制具有年份的时间序列
- c - 将硒与 C 一起使用
- azure - 吞吐量单元和分区计数
- reactjs - 我应该将反应过渡组样式类放在 scss 中的哪个位置?