How do I copy a file in Python?How to copy a file along with directory structure/path using python?Python: How to Copy Files FastHow to copy a file to a specific folder in a Python script?Copying and renaming excel files with PythonWriting from .txt to .md in pythonHow do I get Python to read and extract words from a text file?How to get python to copy files to desktopPython + OpenCV - Copying an image to some directoryPython copy file but keep originalHow to copy a file in pythonHow do I check whether a file exists without exceptions?Calling an external command in PythonHow can I safely create a nested directory in Python?How can I make a time delay in Python?How do I include a JavaScript file in another JavaScript file?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?How to copy a folder from remote to local using scp?What is the difference between the `COPY` and `ADD` commands in a Dockerfile?
Why do people keep telling me that I am a bad photographer?
Indentation Tex
As a GM, is it bad form to ask for a moment to think when improvising?
Has the United States ever had a non-Christian President?
When does tabularx decide to break the cell entry instead of reducing the columns separation?
Should I simplify my writing in a foreign country?
Python 3 - simple temperature program
Is Benjen dead?
Is there a word for food that's gone 'bad', but is still edible?
How do I calculate how many of an item I'll have in this inventory system?
Does "Captain Marvel" contain spoilers for "Avengers: Infinity War"?
Would you use "llamarse" for an animal's name?
Agena docking and RCS Brakes in First Man
How long would it take for people to notice a mass disappearance?
Change in "can't be countered" wording
Why is "breaking the mould" positively connoted?
Are the Night's Watch still required?
History of the kernel of a homomorphism?
Why symmetry transformations have to commute with Hamiltonian?
Endgame puzzle: How to avoid stalemate and win?
Start job from another SQL server instance
How to deal with employer who keeps me at work after working hours
Notation: What does the tilde bellow of the Expectation mean?
Is there a word that describes the unjustified use of a more complex word?
How do I copy a file in Python?
How to copy a file along with directory structure/path using python?Python: How to Copy Files FastHow to copy a file to a specific folder in a Python script?Copying and renaming excel files with PythonWriting from .txt to .md in pythonHow do I get Python to read and extract words from a text file?How to get python to copy files to desktopPython + OpenCV - Copying an image to some directoryPython copy file but keep originalHow to copy a file in pythonHow do I check whether a file exists without exceptions?Calling an external command in PythonHow can I safely create a nested directory in Python?How can I make a time delay in Python?How do I include a JavaScript file in another JavaScript file?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?How to copy a folder from remote to local using scp?What is the difference between the `COPY` and `ADD` commands in a Dockerfile?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
How do I copy a file in Python?
I couldn't find anything under os
.
python file copy filesystems copyfile
add a comment |
How do I copy a file in Python?
I couldn't find anything under os
.
python file copy filesystems copyfile
87
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58
add a comment |
How do I copy a file in Python?
I couldn't find anything under os
.
python file copy filesystems copyfile
How do I copy a file in Python?
I couldn't find anything under os
.
python file copy filesystems copyfile
python file copy filesystems copyfile
edited Aug 15 '18 at 1:59
Peter Mortensen
14k1987114
14k1987114
asked Sep 23 '08 at 19:23
MattMatt
27.2k254856
27.2k254856
87
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58
add a comment |
87
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58
87
87
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58
add a comment |
15 Answers
15
active
oldest
votes
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
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.
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
|
show 3 more comments
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
@jezrael Extracted from the doc:dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)
– Conchylicultor
Feb 1 '17 at 21:48
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
|
show 2 more comments
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
- it allows
dst
to be a directory (instead of the complete target filename), in which case the basename ofsrc
is used for creating the new file; - it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).
Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
Your answer is a bit deceptive. Your choice of words forshutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this casedir
must already exist as a directory or elsefile.ext
will be copied to a new file calleddir
.
– Matthew Alpert
Oct 31 '13 at 19:29
16
I am trying to randomly copy 100k files from 1 million files.copyfile
is considerably faster thancopy2
– Vijay
May 7 '14 at 8:31
4
am I correct to assume thatshutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?
– Zak
Aug 19 '15 at 18:56
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
|
show 5 more comments
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.
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
If you want to copy by filename you could do something like this:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there'sshutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
Yes, I'm not sure why you wouldn't just copy the source ofshutil.copyfileobj
. Also, you don't have anytry, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like howshutil.copyfile
wrapsshutil.copyfileobj
.
– ErlVolton
Oct 28 '14 at 18:48
|
show 2 more comments
You can use one of the copy functions from the shutil
package:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
add a comment |
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
module
import os
import shutil
import subprocess
1) Copying files using shutil
module
shutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
2) Copying files using os
module
os.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
3) Copying files using subprocess
module
subprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.
– Marcel Waldvogel
Apr 29 at 3:03
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. andcheck_output
doesn't return the status but the output (which is empty in the case ofcopy/cp
)
– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
add a comment |
Use the shutil module.
copyfile(src, dst)
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.
add a comment |
Directory and File copy example - From Tim Golden's Python Stuff:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
add a comment |
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
Even whenshutil
is not available -subprocess.run()
(withoutshell=True
!) is the better alternative toos.system()
.
– maxschlepzig
Jul 9 '17 at 11:52
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying,shutil
and friends are recommended over calling an external program.)
– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
add a comment |
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.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
2
this seems a little redundant since the writer should handle buffering.for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try withoutput.write(read(n)); output.flush()
wheren
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.
– owns
Jun 12 '15 at 17:30
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,writelines()
has shown slightly better performance overwrite()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.
– ytpillai
Nov 30 '16 at 3:33
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
|
show 1 more comment
from subprocess import call
call("cp -p <file> <file>", shell=True)
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
Such acall
is unsecure. Please refere to the subproces docu about it.
– buhtz
Apr 2 '17 at 7:57
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
add a comment |
Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.
shutil_methods =
'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
Secondly, explain methods of copy in exmaples:
shutil.copyfileobj(fsrc, fdst[, length])
manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree()``
Recursively copy an entire directory tree rooted at src, returning the destination directory
add a comment |
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
Is that true? I think.read()
and.write()
are buffered by default (at least for CPython).
– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned byopen()
does buffered IO, by default doesn't help you here, becauseread()
is specified as: 'If n is negative or omitted, read until EOF.' That means that theread()
returns the complete file content as a string.
– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
add a comment |
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
Isn't that missing the.close()
on all of thoseopen(...)
s?
– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Usingwith
(as in the example above) is recommended and not more complicated. Usingread()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like fromshutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader
– Marcel Waldvogel
Apr 29 at 3:17
|
show 1 more comment
As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
will overwrite whatever was at the destination's location
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions fromshutil
handles all the special cases for you and gives you peace of mind.
– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
add a comment |
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?
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
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.
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
|
show 3 more comments
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
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.
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
|
show 3 more comments
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
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.
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
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.
edited Mar 31 at 5:14
Mr. Me
3,37012337
3,37012337
answered Sep 23 '08 at 19:25
SwatiSwati
27.2k43152
27.2k43152
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
|
show 3 more comments
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
101
101
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
What is the difference between copy and copyfile?
– Matt
Sep 23 '08 at 19:47
313
313
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
in copy(src, dst) the dst can be a directory.
– Owen
Sep 23 '08 at 19:51
28
28
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
Note that not all metadata will be copied, depending on your platform.
– Kevin Horn
Oct 19 '09 at 20:50
14
14
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
@MonaJalal It's case sensitive, don't use capital F.
– antonagestam
Dec 22 '17 at 17:39
3
3
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
Note that it is not an atomic operation. Take care using it in a threaded application.
– Waterbyte
Oct 22 '18 at 11:53
|
show 3 more comments
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
@jezrael Extracted from the doc:dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)
– Conchylicultor
Feb 1 '17 at 21:48
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
|
show 2 more comments
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
@jezrael Extracted from the doc:dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)
– Conchylicultor
Feb 1 '17 at 21:48
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
|
show 2 more comments
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘
┌──────────────────┬───────────────┬──────────────────┬──────────────┬───────────┐
│ Function │Copies metadata│Copies permissions│Can use buffer│Dest dir OK│
├──────────────────┼───────────────┼──────────────────┼──────────────┼───────────┤
│shutil.copy │ No │ Yes │ No │ Yes │
│shutil.copyfile │ No │ No │ No │ No │
│shutil.copy2 │ Yes │ Yes │ No │ Yes │
│shutil.copyfileobj│ No │ No │ Yes │ No │
└──────────────────┴───────────────┴──────────────────┴──────────────┴───────────┘
edited Oct 24 '18 at 1:59
jcrs
1539
1539
answered May 20 '15 at 20:01
jezraeljezrael
365k26332415
365k26332415
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
@jezrael Extracted from the doc:dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)
– Conchylicultor
Feb 1 '17 at 21:48
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
|
show 2 more comments
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
@jezrael Extracted from the doc:dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)
– Conchylicultor
Feb 1 '17 at 21:48
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
6
6
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
Could also add that copy and copy2 accept directory as destination contrary to copyfile which require to specify the complete name.
– Conchylicultor
Oct 10 '16 at 18:47
2
2
@jezrael Extracted from the doc:
dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)– Conchylicultor
Feb 1 '17 at 21:48
@jezrael Extracted from the doc:
dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path.
(here: docs.python.org/3/library/shutil.html#shutil.copyfile)– Conchylicultor
Feb 1 '17 at 21:48
7
7
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
Now this is just bad, bad API design.
– One Man Monkey Squad
Jan 16 at 13:51
2
2
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
What does the "Dest dir OK" column indicate? Does it mean it doesn't check if the destination directory is OK before copying?
– Katie S
Feb 7 at 22:00
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
According to your table the copyfile is totally useless !! while in the previous answer with 2115 votes, it's the first suggested !! and also this answer has got votes !! it's confusing !!!!
– FabioSpaghetti
Feb 8 at 14:29
|
show 2 more comments
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
- it allows
dst
to be a directory (instead of the complete target filename), in which case the basename ofsrc
is used for creating the new file; - it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).
Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
Your answer is a bit deceptive. Your choice of words forshutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this casedir
must already exist as a directory or elsefile.ext
will be copied to a new file calleddir
.
– Matthew Alpert
Oct 31 '13 at 19:29
16
I am trying to randomly copy 100k files from 1 million files.copyfile
is considerably faster thancopy2
– Vijay
May 7 '14 at 8:31
4
am I correct to assume thatshutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?
– Zak
Aug 19 '15 at 18:56
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
|
show 5 more comments
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
- it allows
dst
to be a directory (instead of the complete target filename), in which case the basename ofsrc
is used for creating the new file; - it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).
Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
Your answer is a bit deceptive. Your choice of words forshutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this casedir
must already exist as a directory or elsefile.ext
will be copied to a new file calleddir
.
– Matthew Alpert
Oct 31 '13 at 19:29
16
I am trying to randomly copy 100k files from 1 million files.copyfile
is considerably faster thancopy2
– Vijay
May 7 '14 at 8:31
4
am I correct to assume thatshutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?
– Zak
Aug 19 '15 at 18:56
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
|
show 5 more comments
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
- it allows
dst
to be a directory (instead of the complete target filename), in which case the basename ofsrc
is used for creating the new file; - it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).
Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
- it allows
dst
to be a directory (instead of the complete target filename), in which case the basename ofsrc
is used for creating the new file; - it preserves the original modification and access info (mtime and atime) in the file metadata (however, this comes with a slight overhead).
Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
edited Mar 13 '17 at 17:56
Sheljohn
4,08622656
4,08622656
answered Sep 23 '08 at 19:29
unmountedunmounted
23.6k144957
23.6k144957
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
Your answer is a bit deceptive. Your choice of words forshutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this casedir
must already exist as a directory or elsefile.ext
will be copied to a new file calleddir
.
– Matthew Alpert
Oct 31 '13 at 19:29
16
I am trying to randomly copy 100k files from 1 million files.copyfile
is considerably faster thancopy2
– Vijay
May 7 '14 at 8:31
4
am I correct to assume thatshutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?
– Zak
Aug 19 '15 at 18:56
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
|
show 5 more comments
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
Your answer is a bit deceptive. Your choice of words forshutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this casedir
must already exist as a directory or elsefile.ext
will be copied to a new file calleddir
.
– Matthew Alpert
Oct 31 '13 at 19:29
16
I am trying to randomly copy 100k files from 1 million files.copyfile
is considerably faster thancopy2
– Vijay
May 7 '14 at 8:31
4
am I correct to assume thatshutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?
– Zak
Aug 19 '15 at 18:56
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
3
3
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
Although the documentation warns that copy2 does not preserve all metadata, this is just what I needed as I wanted the items you list. Thanks!
– sage
Jun 23 '11 at 17:33
20
20
Your answer is a bit deceptive. Your choice of words for
shutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this case dir
must already exist as a directory or else file.ext
will be copied to a new file called dir
.– Matthew Alpert
Oct 31 '13 at 19:29
Your answer is a bit deceptive. Your choice of words for
shutil.copy2('/dir/file.ext', '/new/dir')
suggests that copy2 will create a new directory. But in this case dir
must already exist as a directory or else file.ext
will be copied to a new file called dir
.– Matthew Alpert
Oct 31 '13 at 19:29
16
16
I am trying to randomly copy 100k files from 1 million files.
copyfile
is considerably faster than copy2
– Vijay
May 7 '14 at 8:31
I am trying to randomly copy 100k files from 1 million files.
copyfile
is considerably faster than copy2
– Vijay
May 7 '14 at 8:31
4
4
am I correct to assume that
shutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?– Zak
Aug 19 '15 at 18:56
am I correct to assume that
shutil.copy2('/dir/file.ext', '/new/dir/')
(with slash after the target path) will remove the ambiguity over whether to copy to a new file called "dir" or to put the file into a directory of that name?– Zak
Aug 19 '15 at 18:56
1
1
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
@Vijay I believe this overhead is due to copying the metadata.
– Sheljohn
Mar 13 '17 at 17:57
|
show 5 more comments
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.
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
If you want to copy by filename you could do something like this:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there'sshutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
Yes, I'm not sure why you wouldn't just copy the source ofshutil.copyfileobj
. Also, you don't have anytry, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like howshutil.copyfile
wrapsshutil.copyfileobj
.
– ErlVolton
Oct 28 '14 at 18:48
|
show 2 more comments
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.
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
If you want to copy by filename you could do something like this:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there'sshutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
Yes, I'm not sure why you wouldn't just copy the source ofshutil.copyfileobj
. Also, you don't have anytry, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like howshutil.copyfile
wrapsshutil.copyfileobj
.
– ErlVolton
Oct 28 '14 at 18:48
|
show 2 more comments
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.
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
If you want to copy by filename you could do something like this:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
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.
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
If you want to copy by filename you could do something like this:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
edited Apr 10 '18 at 15:27
Eric O Lebigot
58k36171220
58k36171220
answered Sep 24 '08 at 7:21
pi.pi.
13.9k53052
13.9k53052
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there'sshutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
Yes, I'm not sure why you wouldn't just copy the source ofshutil.copyfileobj
. Also, you don't have anytry, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like howshutil.copyfile
wrapsshutil.copyfileobj
.
– ErlVolton
Oct 28 '14 at 18:48
|
show 2 more comments
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there'sshutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
Yes, I'm not sure why you wouldn't just copy the source ofshutil.copyfileobj
. Also, you don't have anytry, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like howshutil.copyfile
wrapsshutil.copyfileobj
.
– ErlVolton
Oct 28 '14 at 18:48
24
24
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
I noticed a while ago that the module is called shutil (singular) and not shutils (plural), and indeed it is in Python 2.3. Nevertheless I leave this function here as an example.
– pi.
Mar 31 '09 at 15:20
3
3
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
Copying a file's contents is a straightforward operation. Copying the file with its metadata is anything but straightforward, even more so if you want to be cross-platform.
– LaC
Jan 16 '12 at 18:01
2
2
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
True. Looking at the shutil docs, the copyfile function also won't copy metadata.
– pi.
Jan 17 '12 at 15:08
BTW, if you want to copy the contents between two file-like objects, there's
shutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
BTW, if you want to copy the contents between two file-like objects, there's
shutil.copyfileobj(fsrc, fdst)
– Haroldo_OK
Aug 19 '14 at 13:14
2
2
Yes, I'm not sure why you wouldn't just copy the source of
shutil.copyfileobj
. Also, you don't have any try, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like how shutil.copyfile
wraps shutil.copyfileobj
.– ErlVolton
Oct 28 '14 at 18:48
Yes, I'm not sure why you wouldn't just copy the source of
shutil.copyfileobj
. Also, you don't have any try, finally
to handle closing the files after exceptions. I would say however, that your function shouldn't be responsible for opening and closing the files at all. That should go in a wrapper function, like how shutil.copyfile
wraps shutil.copyfileobj
.– ErlVolton
Oct 28 '14 at 18:48
|
show 2 more comments
You can use one of the copy functions from the shutil
package:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
add a comment |
You can use one of the copy functions from the shutil
package:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
add a comment |
You can use one of the copy functions from the shutil
package:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
You can use one of the copy functions from the shutil
package:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
shutil.copy ✔ ✔ ☐ ☐
shutil.copy2 ✔ ✔ ☐ ✔
shutil.copyfile ☐ ☐ ☐ ☐
shutil.copyfileobj ☐ ☐ ✔ ☐
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Example:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
edited Aug 15 '18 at 17:26
answered Jul 9 '17 at 11:50
maxschlepzigmaxschlepzig
14.5k775112
14.5k775112
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
add a comment |
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
3
3
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
Just curious, how did you generate that table?
– lightalchemist
Dec 2 '18 at 7:40
1
1
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
@lightalchemist I just used vim as a scratchpad, copied the used unicode symbols from a wikipedia table and copied the result into the stackoverflow editor for final polishing.
– maxschlepzig
Dec 2 '18 at 17:02
add a comment |
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
module
import os
import shutil
import subprocess
1) Copying files using shutil
module
shutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
2) Copying files using os
module
os.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
3) Copying files using subprocess
module
subprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.
– Marcel Waldvogel
Apr 29 at 3:03
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. andcheck_output
doesn't return the status but the output (which is empty in the case ofcopy/cp
)
– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
add a comment |
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
module
import os
import shutil
import subprocess
1) Copying files using shutil
module
shutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
2) Copying files using os
module
os.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
3) Copying files using subprocess
module
subprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.
– Marcel Waldvogel
Apr 29 at 3:03
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. andcheck_output
doesn't return the status but the output (which is empty in the case ofcopy/cp
)
– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
add a comment |
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
module
import os
import shutil
import subprocess
1) Copying files using shutil
module
shutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
2) Copying files using os
module
os.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
3) Copying files using subprocess
module
subprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
In Python, you can copy the files using
shutil
moduleos
modulesubprocess
module
import os
import shutil
import subprocess
1) Copying files using shutil
module
shutil.copyfile
signature
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
shutil.copy
signature
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
shutil.copy2
signature
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
shutil.copyfileobj
signature
shutil.copyfileobj(src_file_object, dest_file_object[, length])
# example
file_src = 'source.txt'
f_src = open(file_src, 'rb')
file_dest = 'destination.txt'
f_dest = open(file_dest, 'wb')
shutil.copyfileobj(f_src, f_dest)
2) Copying files using os
module
os.popen
signature
os.popen(cmd[, mode[, bufsize]])
# example
# In Unix/Linux
os.popen('cp source.txt destination.txt')
# In Windows
os.popen('copy source.txt destination.txt')
os.system
signature
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
3) Copying files using subprocess
module
subprocess.call
signature
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)
subprocess.check_output
signature
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)
# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)
answered Jan 22 '18 at 3:05
kmario23kmario23
20.3k56680
20.3k56680
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.
– Marcel Waldvogel
Apr 29 at 3:03
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. andcheck_output
doesn't return the status but the output (which is empty in the case ofcopy/cp
)
– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
add a comment |
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.
– Marcel Waldvogel
Apr 29 at 3:03
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. andcheck_output
doesn't return the status but the output (which is empty in the case ofcopy/cp
)
– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
2
2
Using single-string commands is bad coding style (flexibility, reliability and security), instead use
['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.– Marcel Waldvogel
Apr 29 at 3:03
Using single-string commands is bad coding style (flexibility, reliability and security), instead use
['copy', sourcefile, destfile]
syntax wherever possible, especially if the parameters are from user input.– Marcel Waldvogel
Apr 29 at 3:03
1
1
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
Why do you list so many bad alternatives to the shutil copy functions?
– maxschlepzig
Apr 29 at 11:08
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
shutil is built-in, no need to provide non-portable alternatives. The answer could be actually improved by removing the system dependent solutions, and after that removal, this answer is just a copy of the existing answers / a copy of the documentation.
– Jean-François Fabre♦
Apr 29 at 17:19
os.popen
is deprecated for a while now. and check_output
doesn't return the status but the output (which is empty in the case of copy/cp
)– Jean-François Fabre♦
Apr 29 at 18:12
os.popen
is deprecated for a while now. and check_output
doesn't return the status but the output (which is empty in the case of copy/cp
)– Jean-François Fabre♦
Apr 29 at 18:12
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
@Jean-FrançoisFabre thanks for taking your time to review! I will get back to this in three days (because of a deadline).
– kmario23
Apr 29 at 20:03
add a comment |
Use the shutil module.
copyfile(src, dst)
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.
add a comment |
Use the shutil module.
copyfile(src, dst)
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.
add a comment |
Use the shutil module.
copyfile(src, dst)
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.
Use the shutil module.
copyfile(src, dst)
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.
edited Sep 7 '14 at 13:06
flying sheep
4,62543655
4,62543655
answered Sep 23 '08 at 19:27
Airsource LtdAirsource Ltd
24.2k136474
24.2k136474
add a comment |
add a comment |
Directory and File copy example - From Tim Golden's Python Stuff:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
add a comment |
Directory and File copy example - From Tim Golden's Python Stuff:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
add a comment |
Directory and File copy example - From Tim Golden's Python Stuff:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
Directory and File copy example - From Tim Golden's Python Stuff:
http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
answered Mar 15 '11 at 10:11
Noam ManosNoam Manos
6,29413541
6,29413541
add a comment |
add a comment |
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
Even whenshutil
is not available -subprocess.run()
(withoutshell=True
!) is the better alternative toos.system()
.
– maxschlepzig
Jul 9 '17 at 11:52
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying,shutil
and friends are recommended over calling an external program.)
– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
add a comment |
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
Even whenshutil
is not available -subprocess.run()
(withoutshell=True
!) is the better alternative toos.system()
.
– maxschlepzig
Jul 9 '17 at 11:52
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying,shutil
and friends are recommended over calling an external program.)
– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
add a comment |
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
edited Dec 19 '14 at 23:23
James Donnelly
102k22159174
102k22159174
answered Dec 19 '14 at 23:18
markmark
23522
23522
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
Even whenshutil
is not available -subprocess.run()
(withoutshell=True
!) is the better alternative toos.system()
.
– maxschlepzig
Jul 9 '17 at 11:52
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying,shutil
and friends are recommended over calling an external program.)
– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
add a comment |
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
Even whenshutil
is not available -subprocess.run()
(withoutshell=True
!) is the better alternative toos.system()
.
– maxschlepzig
Jul 9 '17 at 11:52
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying,shutil
and friends are recommended over calling an external program.)
– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
9
9
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
4
4
Even when
shutil
is not available - subprocess.run()
(without shell=True
!) is the better alternative to os.system()
.– maxschlepzig
Jul 9 '17 at 11:52
Even when
shutil
is not available - subprocess.run()
(without shell=True
!) is the better alternative to os.system()
.– maxschlepzig
Jul 9 '17 at 11:52
1
1
shutil is more portable
– Hiadore
Mar 12 at 9:07
shutil is more portable
– Hiadore
Mar 12 at 9:07
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying, shutil
and friends are recommended over calling an external program.)– Marcel Waldvogel
Apr 29 at 3:09
subprocess.run()
as suggested by @maxschlepzig is a big step forward, when calling external programs. For flexibility and security however, use the ['cp', rawfile, 'rawdata.dat']
form of passing the command line. (However, for copying, shutil
and friends are recommended over calling an external program.)– Marcel Waldvogel
Apr 29 at 3:09
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
try that with filenames with spaces in it.
– Jean-François Fabre♦
Apr 29 at 17:21
add a comment |
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.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
2
this seems a little redundant since the writer should handle buffering.for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try withoutput.write(read(n)); output.flush()
wheren
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.
– owns
Jun 12 '15 at 17:30
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,writelines()
has shown slightly better performance overwrite()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.
– ytpillai
Nov 30 '16 at 3:33
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
|
show 1 more comment
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.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
2
this seems a little redundant since the writer should handle buffering.for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try withoutput.write(read(n)); output.flush()
wheren
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.
– owns
Jun 12 '15 at 17:30
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,writelines()
has shown slightly better performance overwrite()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.
– ytpillai
Nov 30 '16 at 3:33
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
|
show 1 more comment
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.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
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.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
answered May 25 '15 at 5:11
ytpillaiytpillai
2,3481835
2,3481835
2
this seems a little redundant since the writer should handle buffering.for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try withoutput.write(read(n)); output.flush()
wheren
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.
– owns
Jun 12 '15 at 17:30
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,writelines()
has shown slightly better performance overwrite()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.
– ytpillai
Nov 30 '16 at 3:33
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
|
show 1 more comment
2
this seems a little redundant since the writer should handle buffering.for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try withoutput.write(read(n)); output.flush()
wheren
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.
– owns
Jun 12 '15 at 17:30
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,writelines()
has shown slightly better performance overwrite()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.
– ytpillai
Nov 30 '16 at 3:33
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
2
2
this seems a little redundant since the writer should handle buffering.
for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try with output.write(read(n)); output.flush()
where n
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.– owns
Jun 12 '15 at 17:30
this seems a little redundant since the writer should handle buffering.
for l in open('file.txt','r'): output.write(l)
should work find; just setup the output stream buffer to your needs. or you can go by the bytes by looping over a try with output.write(read(n)); output.flush()
where n
is the number of bytes you'd like to write at a time. both of these also don't have an condition to check which is a bonus.– owns
Jun 12 '15 at 17:30
1
1
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Yes, but I thought that maybe this could be easier to understand because it copies entire lines rather than parts of them (in case we don't know how many bytes each line is).
– ytpillai
Jun 13 '15 at 18:42
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
Very true. Coding for teaching and coding for efficiency are very different.
– owns
Jun 15 '15 at 17:47
@owns To add to this question a year later,
writelines()
has shown slightly better performance over write()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.– ytpillai
Nov 30 '16 at 3:33
@owns To add to this question a year later,
writelines()
has shown slightly better performance over write()
since we don't waste time consistently opening a new filestream, and instead write new lines as one large bytefeed.– ytpillai
Nov 30 '16 at 3:33
1
1
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
looking at the source - writelines calls write, hg.python.org/cpython/file/c6880edaf6f3/Modules/_io/bytesio.c. Also, the file stream is already open, so write wouldn't need to reopen it every time.
– owns
May 3 '17 at 0:24
|
show 1 more comment
from subprocess import call
call("cp -p <file> <file>", shell=True)
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
Such acall
is unsecure. Please refere to the subproces docu about it.
– buhtz
Apr 2 '17 at 7:57
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
add a comment |
from subprocess import call
call("cp -p <file> <file>", shell=True)
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
Such acall
is unsecure. Please refere to the subproces docu about it.
– buhtz
Apr 2 '17 at 7:57
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
add a comment |
from subprocess import call
call("cp -p <file> <file>", shell=True)
from subprocess import call
call("cp -p <file> <file>", shell=True)
answered Apr 4 '16 at 7:08
deepdivedeepdive
2,26621627
2,26621627
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
Such acall
is unsecure. Please refere to the subproces docu about it.
– buhtz
Apr 2 '17 at 7:57
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
add a comment |
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
Such acall
is unsecure. Please refere to the subproces docu about it.
– buhtz
Apr 2 '17 at 7:57
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
10
10
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
This depends on the platform, so i would not use is.
– Kevin Meier
Sep 13 '16 at 10:02
5
5
Such a
call
is unsecure. Please refere to the subproces docu about it.– buhtz
Apr 2 '17 at 7:57
Such a
call
is unsecure. Please refere to the subproces docu about it.– buhtz
Apr 2 '17 at 7:57
1
1
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
this is not portable, and unnecessary since you can just use shutil.
– Corey Goldberg
Jun 12 '17 at 14:05
2
2
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Hmm why Python, then?
– Baris Demiray
Jul 7 '17 at 9:29
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
Maybe detect the operating system before starting (whether it's DOS or Unix, because those are the two most used)
– MilkyWay90
Nov 9 '18 at 15:51
add a comment |
Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.
shutil_methods =
'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
Secondly, explain methods of copy in exmaples:
shutil.copyfileobj(fsrc, fdst[, length])
manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree()``
Recursively copy an entire directory tree rooted at src, returning the destination directory
add a comment |
Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.
shutil_methods =
'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
Secondly, explain methods of copy in exmaples:
shutil.copyfileobj(fsrc, fdst[, length])
manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree()``
Recursively copy an entire directory tree rooted at src, returning the destination directory
add a comment |
Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.
shutil_methods =
'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
Secondly, explain methods of copy in exmaples:
shutil.copyfileobj(fsrc, fdst[, length])
manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree()``
Recursively copy an entire directory tree rooted at src, returning the destination directory
Firstly, I made an exhaustive cheatsheet of shutil methods for your reference.
shutil_methods =
'copy':['shutil.copyfileobj',
'shutil.copyfile',
'shutil.copymode',
'shutil.copystat',
'shutil.copy',
'shutil.copy2',
'shutil.copytree',],
'move':['shutil.rmtree',
'shutil.move',],
'exception': ['exception shutil.SameFileError',
'exception shutil.Error'],
'others':['shutil.disk_usage',
'shutil.chown',
'shutil.which',
'shutil.ignore_patterns',]
Secondly, explain methods of copy in exmaples:
shutil.copyfileobj(fsrc, fdst[, length])
manipulate opened objects
In [3]: src = '~/Documents/Head+First+SQL.pdf'
In [4]: dst = '~/desktop'
In [5]: shutil.copyfileobj(src, dst)
AttributeError: 'str' object has no attribute 'read'
#copy the file object
In [7]: with open(src, 'rb') as f1,open(os.path.join(dst,'test.pdf'), 'wb') as f2:
...: shutil.copyfileobj(f1, f2)
In [8]: os.stat(os.path.join(dst,'test.pdf'))
Out[8]: os.stat_result(st_mode=33188, st_ino=8598319475, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067347, st_mtime=1516067335, st_ctime=1516067345)
shutil.copyfile(src, dst, *, follow_symlinks=True)
Copy and rename
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
shutil.copy()
Copy without preseving the metadata
In [10]: shutil.copy(src, dst)
Out[10]: ~/desktop/Head+First+SQL.pdf'
#check their metadata
In [25]: os.stat(src)
Out[25]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066425, st_mtime=1493698739, st_ctime=1514871215)
In [26]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[26]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516066427, st_mtime=1516066425, st_ctime=1516066425)
# st_atime,st_mtime,st_ctime changed
shutil.copy2()
Copy with preseving the metadata
In [30]: shutil.copy2(src, dst)
Out[30]: ~/desktop/Head+First+SQL.pdf'
In [31]: os.stat(src)
Out[31]: os.stat_result(st_mode=33188, st_ino=597749, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067055, st_mtime=1493698739, st_ctime=1514871215)
In [32]: os.stat(os.path.join(dst, 'Head+First+SQL.pdf'))
Out[32]: os.stat_result(st_mode=33188, st_ino=8598313736, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=13507926, st_atime=1516067063, st_mtime=1493698739, st_ctime=1516067055)
# Preseved st_mtime
- `shutil.copytree()``
Recursively copy an entire directory tree rooted at src, returning the destination directory
answered Jan 16 '18 at 3:25
JawSawJawSaw
5,08311941
5,08311941
add a comment |
add a comment |
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
Is that true? I think.read()
and.write()
are buffered by default (at least for CPython).
– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned byopen()
does buffered IO, by default doesn't help you here, becauseread()
is specified as: 'If n is negative or omitted, read until EOF.' That means that theread()
returns the complete file content as a string.
– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
add a comment |
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
Is that true? I think.read()
and.write()
are buffered by default (at least for CPython).
– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned byopen()
does buffered IO, by default doesn't help you here, becauseread()
is specified as: 'If n is negative or omitted, read until EOF.' That means that theread()
returns the complete file content as a string.
– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
add a comment |
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
For small files and using only python built-ins, you can use the following one-liner:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
As @maxschlepzig mentioned in the comments below, this is not optimal way for applications where the file is too large or when memory is critical, thus Swati's answer should be preferred.
edited Apr 29 at 18:36
answered Aug 15 '17 at 13:46
yellow01yellow01
889823
889823
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
Is that true? I think.read()
and.write()
are buffered by default (at least for CPython).
– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned byopen()
does buffered IO, by default doesn't help you here, becauseread()
is specified as: 'If n is negative or omitted, read until EOF.' That means that theread()
returns the complete file content as a string.
– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
add a comment |
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
Is that true? I think.read()
and.write()
are buffered by default (at least for CPython).
– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned byopen()
does buffered IO, by default doesn't help you here, becauseread()
is specified as: 'If n is negative or omitted, read until EOF.' That means that theread()
returns the complete file content as a string.
– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
3
3
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
This reads the complete source file into memory before writing it back. Thus, this unnecessarily wastes memory for all but the smallest file copy operations.
– maxschlepzig
Oct 2 '17 at 7:11
1
1
Is that true? I think
.read()
and .write()
are buffered by default (at least for CPython).– soundstripe
Nov 17 '17 at 1:39
Is that true? I think
.read()
and .write()
are buffered by default (at least for CPython).– soundstripe
Nov 17 '17 at 1:39
@soundstripe, Of course this is true. The fact that the file object returned by
open()
does buffered IO, by default doesn't help you here, because read()
is specified as: 'If n is negative or omitted, read until EOF.' That means that the read()
returns the complete file content as a string.– maxschlepzig
Apr 29 at 11:00
@soundstripe, Of course this is true. The fact that the file object returned by
open()
does buffered IO, by default doesn't help you here, because read()
is specified as: 'If n is negative or omitted, read until EOF.' That means that the read()
returns the complete file content as a string.– maxschlepzig
Apr 29 at 11:00
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
@maxschlepzig I get your point and I admit I wasn't aware of it. The reason I provided this answer was in case someone wanted to do a simple file copy using only built-ins, without needing to import a module for it. Of course memory optimization should not be a concern if you want this option. Anyways thank you for clearing that out. I updated the answer accordingly.
– yellow01
Apr 29 at 18:36
add a comment |
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
Isn't that missing the.close()
on all of thoseopen(...)
s?
– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Usingwith
(as in the example above) is recommended and not more complicated. Usingread()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like fromshutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader
– Marcel Waldvogel
Apr 29 at 3:17
|
show 1 more comment
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
Isn't that missing the.close()
on all of thoseopen(...)
s?
– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Usingwith
(as in the example above) is recommended and not more complicated. Usingread()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like fromshutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader
– Marcel Waldvogel
Apr 29 at 3:17
|
show 1 more comment
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
edited Apr 29 at 18:15
Jean-François Fabre♦
107k1060118
107k1060118
answered Mar 23 at 0:46
Sundeep BorraSundeep Borra
9951021
9951021
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
Isn't that missing the.close()
on all of thoseopen(...)
s?
– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Usingwith
(as in the example above) is recommended and not more complicated. Usingread()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like fromshutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader
– Marcel Waldvogel
Apr 29 at 3:17
|
show 1 more comment
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
Isn't that missing the.close()
on all of thoseopen(...)
s?
– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Usingwith
(as in the example above) is recommended and not more complicated. Usingread()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like fromshutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader
– Marcel Waldvogel
Apr 29 at 3:17
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
The idea is nice and the code is beautiful, but a proper copy() function can do more things, such as copying attributes (+x bit), or for example deleting the already-copied bytes in case a disk-full condition is found.
– Raúl Salinas-Monteagudo
Mar 29 at 11:06
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
All answers need explanation, even if it is one sentence. No explanation sets bad precedent and is not helpful in understanding the program. What if a complete Python noob came along and saw this, wanted to use it, but couldn't because they don't understand it? You want to be helpful to all in your answers.
– connectyourcharger
Mar 30 at 22:19
1
1
Isn't that missing the
.close()
on all of those open(...)
s?– luckydonald
Apr 22 at 22:37
Isn't that missing the
.close()
on all of those open(...)
s?– luckydonald
Apr 22 at 22:37
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
No need of .close(), as we are NOT STORING the file pointer object anywhere(neither for the src file nor for the destination file).
– Sundeep Borra
Apr 23 at 21:19
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using
with
(as in the example above) is recommended and not more complicated. Using read()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader– Marcel Waldvogel
Apr 29 at 3:17
AFAIK, it is undefined when the files are actually closed, @SundeepBorra. Using
with
(as in the example above) is recommended and not more complicated. Using read()
on a raw file reads the entire file into memory, which may be too big. Use a standard function like from shutil
so that you and whoever else is involved in the code does not need to worry about special cases. docs.python.org/3/library/io.html#io.BufferedReader– Marcel Waldvogel
Apr 29 at 3:17
|
show 1 more comment
As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
will overwrite whatever was at the destination's location
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions fromshutil
handles all the special cases for you and gives you peace of mind.
– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
add a comment |
As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
will overwrite whatever was at the destination's location
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions fromshutil
handles all the special cases for you and gives you peace of mind.
– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
add a comment |
As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
will overwrite whatever was at the destination's location
As of Python 3.5 you can do the following for small files (ie: text files, small jpegs):
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
will overwrite whatever was at the destination's location
answered Apr 25 at 14:09
MarcMarc
1,5781421
1,5781421
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions fromshutil
handles all the special cases for you and gives you peace of mind.
– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
add a comment |
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions fromshutil
handles all the special cases for you and gives you peace of mind.
– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
1
1
And then someone uses the code (accidentally or purposefully) on a large file… Using functions from
shutil
handles all the special cases for you and gives you peace of mind.– Marcel Waldvogel
Apr 29 at 3:21
And then someone uses the code (accidentally or purposefully) on a large file… Using functions from
shutil
handles all the special cases for you and gives you peace of mind.– Marcel Waldvogel
Apr 29 at 3:21
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
at least it doesn't repeat the same solutions over and over again.
– Jean-François Fabre♦
Apr 29 at 18:16
add a comment |
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?
87
It seems that cp is not a system call and therefore does not belong to the os module. It is a shell command, so it is put in the shutil module.
– waldol1
Oct 16 '13 at 20:58