How do I copy a file in Python? I couldn't find anything under os.
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
|||||
|
|
Copy the contents of the file named |
|||||||||||||||||||||
|
|
|||||||||||||||||
|
|
I suggest using Swati's answer, but supposing you have a text file and don't want to use additional libraries in your code just to copy it, you can use the following one-liner:
|
|||||||||
|
|
You can use one of the copy functions from the
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
|
|||
|
|
|
Here is a short example:
|
|||||||||||||||||||||
|
|
|||||||||||||||||
|
|
Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the shutil stdlib module for that.
If you want to copy by filename you could do something like this:
|
|||||||||||||||||||||
|
|
For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file.
|
|||||||||||||||||||||
|
|
Look at module shutil. It contains function copyfile(src, dst) |
||||
|
|
|
You could use or as I did it,
where This is a Linux only solution |
|||||||||
|
|
Use the shutil module.
Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings. Take a look at filesys for all the file and directory handling functions available in standard Python modules. |
|||||
|
|
Directory and File copy example - From Tim Golden's Python Stuff: http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
|
|||
|
|
protected by jezrael Mar 16 '16 at 11:40
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?