Skip to content
Advertisement

Simple python file copying only working from root

I’m new to python and am trying to just create a folder and copy files inside of it. I can successfully create the folder and can successfully copy another sibling folder in the root directory via this line:

#copy_tree("old-tocopy", "new_folder") # this works

(so folders old-tocopy and new_folder are siblings in the root directory).

However, I’m having trouble copying files into it from another directory when using the tilder (~) symbol to navigate to the directory (although I can CD to it in the terminal as such: cd ~/Documents/hello)

To explain it better, I have this folder on my MacBook:

~/Documents/hello

The hello folder contains a file ‘hello.txt’, subfolder ‘hi’ and ‘hi.txt’ inside the subfolder. But I’m getting this error:

Traceback (most recent call last):
  File "backuper.py", line 10, in <module>
    copy_tree("~/Documents/hello", "new_folder")
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/distutils/dir_util.py", line 123, in copy_tree
    raise DistutilsFileError(
distutils.errors.DistutilsFileError: cannot copy tree '~/Documents/hello': not a directory

Why am I getting this error, and how can it be fixed? And why would it work with the other ‘old-tocopy’ folder that exists inside the same directory as the python script file? The error suggests that the hello folder is not a directory, but I’m pretty sure it is.

Here’s my code:

import os
from distutils.dir_util import copy_tree

#1 - create new folder
if not os.path.exists('new_folder'):
    os.makedirs('new_folder')

#2 - copy files into new folder
#copy_tree("old-tocopy", "new_folder") # this works
copy_tree("~/Documents/hello", "new_folder")

Thank for any help here.

Advertisement

Answer

you cannot use ~ with python, because cd ~ is specific to your bash(or whatever) shell, for python ~ is just literal and hence os.path.isdir("~/Documents/hello") is giving False

you can replace it with a full path like /home/Documents/hello and it will work.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement