shutil.copystat() FileNotFoundError: [Errno 2]没有这样的文件或目录.<



我试图使用shutil.copystat()复制文件。这是我的代码:

import os
from os import path
import shutil
def main():
if path.exists("textfile.txt"):
src = path.realpath("textfile.txt")
dest = src + ".bak"
shutil.copystat(src, dest)

if __name__ == "__main__":
main()
但是,这会导致以下错误:
Traceback (most recent call last):
File "/Users/x/Development/Python/Exercise Files/Ch4/shell_start.py", line 30, in <module>
main()
File "/Users/x/Development/Python/Exercise Files/Ch4/shell_start.py", line 19, in main
shutil.copystat(src, dest)
File "/opt/homebrew/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/shutil.py", line 375, in copystat
lookup("utime")(dst, ns=(st.st_atime_ns, st.st_mtime_ns),
FileNotFoundError: [Errno 2] No such file or directory

我已经打印了路径,两者都是正确的。我的文件结构如下:

/Ch4
/shell_start.py
/textfile.txt

有人知道我在这里做错了什么吗?

Replace:

shutil.copystat(src, dest)

由:

shutil.copy2(src, dest)

如果您想使用shutil.copystat,请执行:

shutil.copy(src, dest)
shutil.copystat(src, dest)

阅读shutil.copy2的文档

shutil.copystat不复制文件,它只在两个现有文件之间复制状态位。你要的是shutil.copy2

相关内容

最新更新