我在编写一些代码时遇到了困难,这些代码旨在将多个文件的“上次修改”日期写入CSV文档。
我有其他一切正常运行,但是这个函数返回:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'filenamesoandso.docx'
这是上下文:
pathList = ["S:\\BUILDING\\",
"S:\\ONGOING PROJECTS\FACILITY OPERATIONS\OPERATIONS\\"
]
def file_date_modified(pathList):
sys.stdout = open("date modified.txt", "w+")
for root, dirs, files, in os.walk(a):
for file in files:
if file.endswith(".pdf"):
print(time.ctime(os.path.getmtime(file)))
if file.endswith(".pptx"):
print(time.ctime(os.path.getmtime(file)))
if file.endswith(".doc"):
print(time.ctime(os.path.getmtime(file)))
if file.endswith(".docx"):
print(time.ctime(os.path.getmtime(file)))
if file.endswith(".xlsx"):
print(time.ctime(os.path.getmtime(file)))
for a in pathList:
file_date_modified()
我意识到这个错误通常表明它正在查找错误的目录,但是无法根据对此处其他问题的回复提出修复。这是我一直使用的另一个功能正常工作的例子,我不确定为什么这个确定了正确的路径而前者没有。
def file_name_print(pathList):
sys.stdout = open("file names.txt", "w+")
for root, dirs, files in os.walk(a):
for file in files:
if file.endswith(".pdf"):
print(os.path.splitext(file)[0])
if file.endswith(".pptx"):
print(os.path.splitext(file)[0])
if file.endswith(".doc"):
print(os.path.splitext(file)[0])
if file.endswith(".docx"):
print(os.path.splitext(file)[0])
if file.endswith(".xlsx"):
print(os.path.splitext(file)[0])
我还是个菜鸟,所以我可能会忽略一些愚蠢的东西。
您可能需要将目录附加到文件名,因为该文件的目录与脚本的当前工作目录不同,如图所示。
在这样做的方式可能是:
for file in files:
file_path = os.path.join(root, file)
if file.endswith(".pdf"):
print(time.ctime(os.path.getmtime(file_path)))
那对你有用吗?