Search code examples
python-3.xcopymoveshutil

python3 shutil error copying from config list


Im trying to copy a file using shutil by reading in a config.dat file.
This file is simply: /home/admin/Documents/file1 /home/admin/Documents/file2

Code does work but it will copy file1 okay but then misses file2 because it see a \n there, which im guessing is because of the new line.

#!/usr/bin/python3
import shutil
data = open("config.dat")
filelist = data.read()
src = filelist
dest = '/home/admin/Documents/backup/'
shutil.copy(src, dest)

Error code im getting :

Traceback (most recent call last):
  File "./testing.py", line 18, in <module>
    shutil.copy(src, dest)
  File "/usr/lib/python3.4/shutil.py", line 229, in copy
    copyfile(src, dst, follow_symlinks=follow_symlinks)
  File "/usr/lib/python3.4/shutil.py", line 108, in copyfile
    with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 
'/home/admin/Documents/file1\n/home/admin/Documents/file2'

I would like the copy of those files to run based on the files from the config.dat folder but it detects a '\n'. Is there a way to fix this?

thanks for the help


Solution

  • Use split('\n') to get a list of files and the iterate that list. You probably want to throw in the file.strip() to get rid of trailing whitespace and empty lines.

    import shutil
    
    
    dest = '/home/admin/Documents/backup/'
    with open('config.dat') as data:
        filelist = data.read().split('\n')
        for file in filelist:
            if file:
                shutil.copy(file.strip(), dest)
    

    Or, if you don't need the filelist after this

    with open('config.dat') as data:
        for file in data:
            if file:
                shutil.copy(file.strip(), dest)