Python实现文件的复制粘贴

用 Python 复制文件的 9 种方法具体是:

shutil copyfile() 
shutil copy() 
shutil copyfileobj() 
shutil copy2()
os popen()
os system() 
threading Thread() 
subprocess call() 
subprocess check_output() 

1.Shutil Copyfile()
1.只有当目标是可写的,这个方法才会将源内容复制到目标位置。如果你没有写入权限,则会导致 IOError 异常。

copyfile(source_file, destination_file)
它将源内容复制到目标文件中。

2.它将源内容复制到目标文件中,如果目标文件不可写入,那么复制操作将导致 IOError 异常。

3.如果源文件和目标文件都相同,它将会返回 SameFileError。

4.但是,如果目标文件之前有不同的名称,那么该副本将会覆盖其内容。

5.如果目标是一个目录,这意味着此方法不会复制到目录,那么会发生 Error 13。

6.它不支持复制诸如字符或块驱动以及管道等文件。

from shutil import copyfile
from sys import exit

source = input("Enter source file with full path: ")
target = input("Enter target file with full path: ")

# adding exception handling
try:
   copyfile(source, target)
except IOError as e:
   print("Unable to copy file. %s" % e)
   exit(1)
except:
   print("Unexpected error:", sys.exc_info())
   exit(1)

print("\nFile copy done!\n")

2.Shutil Copy()方法

copyfile(source_file, [destination_file or dest_dir])

copy() 方法的功能类似于 Unix 中的“cp”命令。这意味着如果目标是一个文件夹,那么它将在其中创建一个与源文件具有相同名称(基本名称)的新文件。此外,该方法会在复制源文件的内容后同步目标文件权限到源文件。

import os
import shutil

source = 'current/test/test.py'
target = '/prod/new'

assert not os.path.isabs(source)
target = os.path.join(target, os.path.dirname(source))

# create the folders if not already exists
os.makedirs(target)

# adding exception handling
try:
   shutil.copy(source, target)
except IOError as e:
   print("Unable to copy file. %s" % e)
except:
   print("Unexpected error:", sys.exc_info())

copy() vs copyfile() :

1.copy() 还可以在复制内容时设置权限位,而 copyfile() 只复制数据。

2.如果目标是目录,则 copy() 将复制文件,而 copyfile() 会失败,出现 Error 13。

3.copyfile() 方法在实现过程中使用 copyfileobj() 方法,而 copy() 方法则是依次使用 copyfile() 和 copymode() 函数。

3.Shutil Copyfileobj()方法

该方法将文件复制到目标路径或者文件对象。如果目标是文件对象,那么你需要在调用 copyfileobj() 之后关闭它。它还假定了一个可选参数(缓冲区大小),你可以用来设置缓冲区长度。这是复制过程中保存在内存中的字节数。系统使用的默认大小是 16KB。

from shutil import copyfileobj
status = False
if isinstance(target, string_types):
   target = open(target, 'wb')
   status = True
try:
   copyfileobj(self.stream, target, buffer_size)
finally:
   if status:
       target.close()

4.Shutil Copy2()方法

虽然 copy2() 方法的功能类似于 copy()。但是它可以在复制数据时获取元数据中添加的访问和修改时间。复制相同的文件会导致 SameFileError 异常。

copy() vs copy2() :
1.copy() 只能设置权限位,而 copy2() 还可以使用时间戳来更新文件元数据。
2.copy() 在函数内部调用 copyfile() 和 copymode(), 而 copy2() 是调用 copystat() 来替换copymode()。

5.Os Popen()方法
该方法创建一个发送或者接受命令的管道。它返回一个打开的并且连接管道的文件对象。你可以根据文件打开模式将其用于读取或者写入比如‘r’(默认)或者‘w’。

os.popen(command[, mode[, bufsize]])

import os
os.popen('copy 1.txt.py 2.txt.py')

6.Os System()方法

这是运行任何系统命令的最常用方式。使用 system() 方法,你可以调用 subshell 中的任何命令。在内部,该方法将调用 C 语言的标准库函数。
该方法返回该命令的退出状态。

import os
os.system('copy 1.txt.py 2.txt.py') 

7.使用异步方式的线程库threading Thread()复制文件

如果你想以异步方式复制文件,那么使用下面的方法。在这里,我们使用 Python 的线程模块在后台进行复制操作。

在使用这种方法时,请确保使用锁定以避免锁死。如果你的应用程序使用多个线程读取/写入文件,就可能会遇到这种情况。

import shutil
from threading import Thread

src="1.txt.py"
dst="3.txt.py"

Thread(target=shutil.copy, args=[src, dst]).start()

8.Subprocess Call()

Subprocess 模块提供了一个简单的接口来处理子进程。它让我们能够启动子进程,连接到子进程的输入/输出/错误管道,并检索返回值。

subprocess 模块旨在替换旧版模块和函数,比如 – os.system, os.spawn*, os.popen*, popen2.*

它使用 call() 方法调用系统命令来执行用户任务。

import subprocess

src="1.txt.py"
dst="2.txt.py"
cmd='copy "%s" "%s"' % (src, dst)

status = subprocess.call(cmd, shell=True)

if status != 0:
    if status < 0:
        print("Killed by signal", status)
    else:
        print("Command failed with return code - ", status)
else:
    print('Execution of %s passed!\n' % cmd)

** subprocess Check_output() **

使用 subprocess 中的 Check_output() 方法,你可以运行外部命令或程序并捕获其输出。它也支持管道。

import os, subprocess

src=os.path.realpath(os.getcwd() + "http://cdn.techbeamers.com/1.txt.py")
dst=os.path.realpath(os.getcwd() + "http://cdn.techbeamers.com/2.txt.py")
cmd='copy "%s" "%s"' % (src, dst)

status = subprocess.check_output(['copy', src, dst], shell=True)

print("status: ", status.decode('utf-8'))

猜你喜欢

转载自blog.csdn.net/liulanba/article/details/114980792