I try to copy a file with pathlib
import pathlib import shutil my_file=pathlib.Path('/etc/hosts') to_file=pathlib.Path('/tmp/foo') shutil.copy(my_file, to_file)
I get this exception:
/home/foo_egs_d/bin/python /home/foo_egs_d/src/test-pathlib-copy.py Traceback (most recent call last): File "/home/foo_egs_d/src/test-pathlib-copy.py", line 6, in <module> shutil.copy(my_file, to_file) File "/usr/lib/python2.7/shutil.py", line 117, in copy if os.path.isdir(dst): File "/home/foo_egs_d/lib/python2.7/genericpath.py", line 41, in isdir st = os.stat(s) TypeError: coercing to Unicode: need string or buffer, PosixPath found Process finished with exit code
... how to copy file with pathlib in Python 2.7?
We have to use shutil. copyfile(src, dst) to copy the file from source to destination. Along with the path, the name of the file with its extension should be written. src = r'C:\Users\Administrator.
Fortunately, if you're coding in Python, the Pathlib module does the heavy lifting by letting you make sure that your file paths work the same in different operating systems. Also, it provides functionalities and operations to help you save time while handling and manipulating paths.
The iterdir yields path objects of the directory contents. list_dirs.py. #!/usr/bin/python from pathlib import Path path = Path('C:/Users/Jano/Documents') dirs = [e for e in path.iterdir() if e.is_dir()] print(dirs) The example prints the subdirectories of the specified directory.
To use shutil.copy
:
import pathlib import shutil my_file = pathlib.Path('/etc/hosts') to_file = pathlib.Path('/tmp/foo') shutil.copy(str(my_file), str(to_file)) # For Python <= 3.7. shutil.copy(my_file, to_file) # For Python 3.8+.
The problem is pathlib.Path
create a PosixPath
object if you're using Unix/Linux, WindowsPath
if you're using Microsoft Windows.
With older versions of Python, shutil.copy
requires a string as its arguments. For them, use the str
function here.
The cause for shutil.copy()
not working is that you are not using the latest Python, Python 3.6 shutil.copy()
can handle Path
objects (or subclasses thereof). That for older versions of Python this throws an error is because those implementations of shutil
expect string arguments for copy
, and not pathlib.Path
type arguments.
What you actually want to be able to write is:
my_file.copy(to_file)
You can subclass Path to include such a method, and adapt the creation of my_file
. I find it easier to just graft/monkey-patch/duck-punch it on the existing pathlib.Path
from pathlib import Path def _copy(self, target): import shutil assert self.is_file() shutil.copy(str(self), str(target)) # str() only there for Python < (3, 6) Path.copy = _copy
You can put this code anywhere you like, as long as it gets executed before calling the .copy
method on any of the Path
instances. The argument to .copy()
can be a file or a directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With