因此,我通常对编码还很陌生,最近选择了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
P.S:我在Windows 10 Pro上使用python 3.7,verzeichnis xyz是我的示例目录 编辑: 上面列出了我如何添加目录和文件以及我的输出
答案 0 :(得分:0)
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))