Thursday, 12 October 2017

How to copy a file to a specific folder in a Python script?

itemprop="text">



I have the path
of a file stored in a variable (say) filePath. I would like to copy that particular file
to another specific folder within a Python script.



I tried



folderPath = (os.getcwd() +
"/folder_name/") #to get the path of the folder
shutil.copyfile(filePath,
folderPath)



But
I got an error IOError: [Errno 21] Is a
directory
.



How can I solve this
?



My question might seem to be a duplicate of
href="https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python">How
do I copy a file in python?
. But actually, I want to copy a file to
a folder/directory whereas most answers to that question
mention copying one file to another
file.


class="post-text" itemprop="text">
class="normal">Answer



Use
shutil.copy(filePath, folderPath) instead of
shutil.copyfile(). This will allow you to specify a folder as
the destination and copies the file including
permissions.






shutil.copy(src, dst, *,
follow_symlinks=True)
:



Copies the
file src to the file or directory dst. src and dst should be strings. If dst specifies a
directory, the file will be copied into dst using the base filename from src. Returns
the path to the newly created file.




...



copy() copies the
file data and the file’s permission mode
(see os.chmod()). Other
metadata, like the file’s creation and modification times, is not preserved. To preserve
all file metadata from the original, use copy2()
instead.





href="https://docs.python.org/3/library/shutil.html#shutil.copy"
rel="noreferrer">https://docs.python.org/3/library/shutil.html#shutil.copy



See
the difference in copying also documented in shutil.copyfile()
itself:





shutil.copyfile(src, dst, *,
follow_symlinks=True)
:




Copy the contents (no metadata) of the file named
src to a file named dst and return dst. src and dst are
path names given as strings. dst must be the complete target file name;
look at shutil.copy() for a copy that accepts a target directory
path
. If src and dst specify the same file, SameFileError is
raised.





href="https://docs.python.org/3/library/shutil.html#shutil.copyfile"
rel="noreferrer">https://docs.python.org/3/library/shutil.html#shutil.copyfile



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...