I have network folder which is mounted in Ubuntu and I can list all the files from but I am trying to copy it to a target folder and it throws error file not found. Below is the code:
import sys
import os
import shutil
SHARED_FOLDER = '/home/john/mnt'
TARGET_FOLDER = "/home/john/Desktop/"
for img in os.listdir(SHARED_FOLDER):
print(img)
shutil.copy(os.path.join(SHARED_FOLDER, img), TARGET_FOLDER)
Error:
2023-04-24_14:37:10_68.png
Traceback (most recent call last):
File "test.py", line 13, in <module>
shutil.copy(os.path.join(SHARED_FOLDER, img), TARGET_FOLDER)
File "/usr/lib/python3.6/shutil.py", line 245, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.6/shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: '/home/john/mnt/2023-04-24_14:37:10_68.png'
I can clearly see files are present in the shared folder but they are not being copied to target folder. This question is similar to How to copy a file from a network share to local disk with variables?
What am I doing wrong?
Please check if it's an issue with your filenames, as it seems to have plenty of special characters. Try renaming it with a simpler name to test.
If it is related to the filename itself -- it might be because it contains special characters like underscores and colons, which might be causing the issue. You can try sanitizing the filenames before copying them. Here's a modified version of your code that replaces colons with underscores:
import sys
import os
import shutil
SHARED_FOLDER = '/home/john/mnt'
TARGET_FOLDER = "/home/john/Desktop/"
def sanitize_filename(filename):
return filename.replace(':', '_')
for img in os.listdir(SHARED_FOLDER):
print(img)
sanitized_img = sanitize_filename(img)
shutil.copy(os.path.join(SHARED_FOLDER, img), os.path.join(TARGET_FOLDER, sanitized_img))
This code first sanitizes the filename by replacing colons with underscores, and then proceeds to copy the file with the sanitized filename. If there are other special characters causing issues, you can extend the sanitize_filename
function to handle them.