发布于 3年前

Python 文件操作:复制文件

我们可以利用_shutil_模块中可用的功能,_shutil_模块是标准库中另一个用于文件操作的有用模块。我们可以copy()通过将源文件和目标文件指定为字符串来在模块中使用该函数。一个简单的例子如下所示。当然,您可以将copy()函数与glob()函数结合使用,以处理具有相同模式的一堆文件。

>>> import shutil
... 
... source_file = "target_folder/hello.txt"
... target_file = "hello2.txt"
... target_file_path = Path(target_file)
... print("* 复制前,文件存在:", target_file_path.exists())
... shutil.copy(source_file, target_file)
... print("* 复制后,文件存在:", target_file_path.exists())
... 
* 复制前,文件存在: False
* 复制后,文件存在: True
©2020 edoou.com   京ICP备16001874号-3