Mat*_*att 2171 python filesystems copy file file-copying
如何在Python中复制文件?
我找不到任何东西os.
Swa*_*ati 2661
shutil有很多方法可以使用.其中之一是:
from shutil import copyfile
copyfile(src, dst)
Run Code Online (Sandbox Code Playgroud)
将命名文件的内容复制到名为src的文件中dst.目的地位置必须是可写的; 否则,IOError将引发例外.如果dst已经存在,则将被替换.使用此功能无法复制特殊文件,如字符或块设备和管道.src并且dst是以字符串形式给出的路径名.
jez*_*ael 1027
??????????????????????????????????????????????????????????????????
? Function ? Copies ? Copies ?Can use? Destination ?
? ?metadata?permissions?buffer ?may be directory?
??????????????????????????????????????????????????????????????????
?shutil.copy ? No ? Yes ? No ? Yes ?
?shutil.copyfile ? No ? No ? No ? No ?
?shutil.copy2 ? Yes ? Yes ? No ? Yes ?
?shutil.copyfileobj? No ? No ? Yes ? No ?
??????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
unm*_*ted 689
copy2(src,dst)通常比copyfile(src,dst)因为更有用:
dst将一个目录(而不是完整的目标文件名),在这种情况下,基本名称的src用于创建新的文件;这是一个简短的例子:
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
Run Code Online (Sandbox Code Playgroud)
max*_*zig 108
您可以使用包中的一个复制功能shutil:
??????????????????????????????????????????????????????????????????????????????
Function preserves supports accepts copies other
permissions directory dest. file obj metadata
??????????????????????????????????????????????????????????????????????????????
shutil.copy ? ? ? ?
shutil.copy2 ? ? ? ?
shutil.copyfile ? ? ? ?
shutil.copyfileobj ? ? ? ?
??????????????????????????????????????????????????????????????????????????????
例:
import shutil
shutil.copy('/etc/hostname', '/var/tmp/testhostname')
Run Code Online (Sandbox Code Playgroud)
pi.*_*pi. 91
复制文件是一个相对简单的操作,如下面的示例所示,但您应该使用shutil stdlib模块.
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)
Run Code Online (Sandbox Code Playgroud)
如果你想通过文件名复制,你可以这样做:
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)
Run Code Online (Sandbox Code Playgroud)
kma*_*o23 82
在Python中,您可以使用复制文件
shutil 模os 模subprocess 模import os
import shutil
import subprocess
Run Code Online (Sandbox Code Playgroud)
shutil模块复制文件shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copyfile('source.txt', 'destination.txt')
Run Code Online (Sandbox Code Playgroud)
shutil.copy 签名
shutil.copy(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy('source.txt', 'destination.txt')
Run Code Online (Sandbox Code Playgroud)
shutil.copy2 签名
shutil.copy2(src_file, dest_file, *, follow_symlinks=True)
# example
shutil.copy2('source.txt', 'destination.txt')
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
os模块复制文件os.popen 签名
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')
Run Code Online (Sandbox Code Playgroud)
os.system 签名
os.system(command)
# In Linux/Unix
os.system('cp source.txt destination.txt')
# In Windows
os.system('copy source.txt destination.txt')
Run Code Online (Sandbox Code Playgroud)
subprocess模块复制文件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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
Air*_*Ltd 64
使用shutil模块.
copyfile(src, dst)
Run Code Online (Sandbox Code Playgroud)
将名为src的文件的内容复制到名为dst的文件中.目的地位置必须是可写的; 否则,将引发IOError异常.如果dst已经存在,它将被替换.使用此功能无法复制特殊文件,如字符或块设备和管道.src和dst是以字符串形式给出的路径名.
查看filesys,了解标准Python模块中可用的所有文件和目录处理函数.
Noa*_*nos 44
目录和文件复制示例 - 来自Tim Golden的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"
Run Code Online (Sandbox Code Playgroud)
Rit*_*ger 22
在 Python 中复制文件有两种最佳方法。
\nshutil模块代码示例:
\nimport shutil\nshutil.copyfile(\'/path/to/file\', \'/path/to/new/file\')\nRun Code Online (Sandbox Code Playgroud)\n除了copyfile之外,还有其他方法可用,例如 copy、copy2 等,但就性能而言,copyfile是最好的,
\nOS模块代码示例:
\nimport os\nos.system(\'cp /path/to/file /path/to/new/file\')\nRun Code Online (Sandbox Code Playgroud)\n另一种方法是使用子进程,但它并不可取,因为它\xe2\x80\x99 是调用方法之一并且不安全。
\nAlg*_*bra 16
首先,我制作了详尽的shutil方法备忘单供您参考.
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',]
}
Run Code Online (Sandbox Code Playgroud)
其次,解释exmaples中的复制方法:
shutil.copyfileobj(fsrc, fdst[, length])操纵打开的对象
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)
Run Code Online (Sandbox Code Playgroud)
shutil.copyfile(src, dst, *, follow_symlinks=True)复制并重命名
In [9]: shutil.copyfile(src, dst)
IsADirectoryError: [Errno 21] Is a directory: ~/desktop'
#so dst should be a filename instead of a directory name
Run Code Online (Sandbox Code Playgroud)
shutil.copy()无需预先设置元数据即可复制
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
Run Code Online (Sandbox Code Playgroud)
shutil.copy2()通过预先设置元数据进行复制
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
Run Code Online (Sandbox Code Playgroud)
- `shutil.copytree()``
递归复制以src为根的整个目录树,返回目标目录
yel*_*w01 14
我建议使用Swati的答案,但假设你有一个文本文件,并且不想在你的代码中使用额外的库来复制它,你可以使用以下单行:
with open(source, 'r') as src, open(dest, 'w') as dst: dst.write(src.read())
Run Code Online (Sandbox Code Playgroud)
小智 13
你可以用 os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
或者就像我做的那样,
os.system('cp '+ rawfile + ' rawdata.dat')
Run Code Online (Sandbox Code Playgroud)
rawfile我在程序中生成的名称在哪里.
这是一个仅限Linux的解决方案
ytp*_*lai 10
对于大文件,我所做的是逐行读取文件并将每行读入数组.然后,一旦阵列达到一定大小,将其附加到新文件.
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
Run Code Online (Sandbox Code Playgroud)
dee*_*ive 10
from subprocess import call
call("cp -p <file> <file>", shell=True)
Run Code Online (Sandbox Code Playgroud)
S47*_*471 10
open(destination, 'wb').write(open(source, 'rb').read())
Run Code Online (Sandbox Code Playgroud)
以读取模式打开源文件,并以写入模式写入目标文件。
这是一个简单的方法,没有任何模块。它类似于这个答案,但如果它是一个不适合 RAM 的大文件,它也有好处:
with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:
while True:
block = f.read(16*1024*1024) # work by blocks of 16 MB
if not block: # end of file
break
g.write(block)
Run Code Online (Sandbox Code Playgroud)
由于我们正在编写一个新文件,它不会保留修改时间等。如果需要,
我们可以使用os.utime它。
万一你已经走到了这一步。答案是你需要完整的路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
Run Code Online (Sandbox Code Playgroud)
从Python 3.5开始,您可以对小文件(例如:文本文件,小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())
Run Code Online (Sandbox Code Playgroud)
write_bytes 将覆盖目的地位置的所有内容
| 归档时间: |
|
| 查看次数: |
1741939 次 |
| 最近记录: |