Search code examples
pythonshutilioerror

python shutil ioerror when using the ~ symbol in filepaths


Python's shutil seems unable to use the ~ symbol for filepaths. This is a common key to use and yet shutil seems to be unable to find the files when this is in the filepath:

where:

file2copy
Out[5]: '~/folder1/folder2/file.txt'

this error is produced:

  File "/home/user/script.py", line 1192, in <module>
    shutil.copy2(file2copy, newpath+'/newfilename.txt')

  File "/home/user/anaconda2/envs/rootclone/lib/python2.7/shutil.py", line 130, in copy2
    copyfile(src, dst)

  File "/home/user/anaconda2/envs/rootclone/lib/python2.7/shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:

IOError: [Errno 2] No such file or directory: '~/folder1/folder2/file.txt'

I'm not sure if this is a bug or simply that ~ keys can't be used in python. Hoping for some resolution to this. I know that I can use exact filepaths to solve this but the ~ key is useful for changing between users etc (without having to reset working directories etc)


Solution

  • ~ is a shell construct.

    You should use os.path.expanduser(), e.g.:

    os.path.expanduser('~/folder1/folder2/file.txt')
    

    Will result in something like:

    '/home/username/folder1/folder2/file.txt'