Reputation: 799
I'm trying to use shutil.copystat() to copy a file. This is my code:
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()
However, this results in the following error:
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/[email protected]/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
I have printed the paths and both are correct. My file structure is as follows:
/Ch4
/shell_start.py
/textfile.txt
Does anyone know what I'm doing wrong here?
Upvotes: 1
Views: 621
Reputation: 54668
shutil.copystat
doesn't copy files, it only copies the status bits between two existing files. What you want is shutil.copy2
.
Upvotes: 1
Reputation: 120391
Replace:
shutil.copystat(src, dest)
by:
shutil.copy2(src, dest)
If you want to use shutil.copystat
, do:
shutil.copy(src, dest)
shutil.copystat(src, dest)
Read the doc of shutil.copy2
Upvotes: 1