How to copy file to path that contains ampersand '&' using Python's shutil?

StackOverflow https://stackoverflow.com/questions/10414580

  •  05-06-2021
  •  | 
  •  

Question

I am complete newbie in Python and have to modify existing Python script. The script copies file to other path like following:

err=shutil.copyfile(src, dst)

This works unless dst contains character like &:

dst = "Y:\R&D\myfile.txt"

In this case I get windows error popup that says

Open file or Read file error
Y:\R

I tried to escape & using back slash, double back slash and wrapping the string with additional quotes: dst = "\"Y:\R&D\myfile.txt\"". Nothing works in last case I get "invalid path" error message from shutil.

How can I solve this problem?

Était-ce utile?

La solution

I doubt that ampersand is supported on most platforms. You will likely have to make a call to a windows specific program. I suggest robocopy since its really good at copying files. If it's not included in your version of windows, you can find it in the windows server administrator toolkit for 2003.

Autres conseils

It works for me if I change all the \ in the filepaths to / (in both src and dst strings). Yes, I know you're using Windows, but filepaths always seem to be less fussy in Python if you use /, even in Windows.

Also, it looks like you're copying to a network drive. Do you get the same problem copying to c:\R&D\?

What flavor of Windows are you using? shutil.copyfile() works fine for me with & in directory names, in both src and dst paths, in both local and network drives on XP -- as long as I use / in place of \.

Easiest solution, signify to python that the string is raw and not to escape it or modify it in any way:

import shutil

src = r"c:\r&d\file.txt"
dst = r"c:\r&d\file2.txt"

err=shutil.copyfile(src, dst)

Try to escape the "\" with "\ \", this command must work (for example):

 shutil.copyfile("Y:\\R&D\\myfile.txt", "C:\\TMP")

Here are few ways to make it work on windows:

  • Approach 1: (already explained)

    import shutil; shutil.copy(src,dest)

    as long as src/dest are using r'c:\r&d\file' string format. It also works with forward "/" slashes as well.

  • Approach 2: Notice use of double quotes instead of single quotes on windows.

    src = r'c:\r & d\src_file'

    os.system('copy "{}" "{}"'.format(src,dest)) 1 file(s) copied

  • Last resort:

    with open(dest, 'wb') as f: f.write(open(src,'rb').read())

Unlike os.system, this preferred implementation subprocess.call could not work with any quoting approach on windows. I always get The specified path is invalid. Did not try on unix.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top