如何在Python中复制文件?


当前回答

目录和文件复制示例,来自Tim Golden的Python Stuff:

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"

其他回答

shutil模块提供了一些对文件的高级操作。它支持文件复制和删除。

请参考下表了解您的用例。

Function Utilize
File Object
Preserve File
Metadata
Preserve
Permissions
Supports
Directory Dest.
shutil.copyfileobj
shutil.copyfile
shutil.copy2
shutil.copy

目录和文件复制示例,来自Tim Golden的Python Stuff:

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"

您可以使用os.system('cp nameoflegatedbyprogram/otherdirectory/')。

或者就像我做的那样,

os.system('cp '+ rawfile + ' rawdata.dat')

其中rawfile是我在程序中生成的名称。

这是一个仅限Linux的解决方案。

万一你走得这么远。答案是您需要整个路径和文件名

import os

shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))

复制文件是一个相对简单的操作,如下面的示例所示,但是您应该使用shutilstdlib模块。

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)

如果要按文件名复制,可以执行以下操作:

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)