I'm making a simple code with the shutil module of copying another contents of a file and had a FileNotFound error, which I want to use the file name instead of pasting the file path every single time. But no matter what I do, I would always need to paste the file path to not get the error.
import shutil
shutil.copyfile("test",'copy.txt') #scr,dst
Error:
Traceback (most recent call last):
File "c:\Users\user\AppData\Local\Programs\Microsoft VS Code\My Projo's (VSCODE)\Python 🐍\Python 🐍 - Lessons\DUPEME", line 9, in <module>
shutil.copyfile("test", "copy.txt")
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\shutil.py", line 260, in copyfile
with open(src, 'rb') as fsrc:
^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'test'
There is no issue with the code, the issue is where you are running the program from, and the existence of the src file. The error "No such file or directory: 'test'" means that python is searching for a file called "test" inside of the current working directory, but is not finding it. This code will work fine from anywhere you run it on the computer, as long as both the "test" file and "copy.txt" files exist in the working directory. It is good practice to dedicate an entire new directory to each project and then place the python script inside it, along with the "test" file and the "copy.txt" file. If all 3 exist and are in the same location and you run the script it will work.
Steps to fix your error:
If you want to change the project structure to allow for the script to be run from anywhere, you can use absolute paths. So let's say the python file is located at D:\scripts and the "test" and "copy.txt" files are located at C:\Users\user\files you can replace the paths in the python code with their absolute paths: shutil.copyfile("C:\Users\user\files\test", C:\Users\user\files\copy.txt"). Then the python script will work even though it's in a completely separate directory.