网络编程
位置:首页>> 网络编程>> Python编程>> 浅谈Python实现2种文件复制的方法

浅谈Python实现2种文件复制的方法

作者:Hank_Gao  发布时间:2021-09-24 00:25:02 

标签:python,复制文件

本文实例主要实现Python中的文件复制操作,有两种方法,具体实现代码如下所示:


#coding:utf-8

# 方法1:使用read()和write()模拟实现文件拷贝

# 创建文件hello.txt
src = file("hello.txt", "w")
li = ["Hello world \n", "Hello China \n"]

src.writelines(li)
src.close()

#把hello.txt 拷贝到hello2.txt

src = file("hello.txt", "r")
dst = file("hello2.txt", "w")

dst.write(src.read())

src.close()
dst.close()

# 方法2:使用shutil模块
# shutil模块是一个文件、目录的管理接口,提供了一些用于复制文件、目录的函数
# copyfile()函数可以实现文件的拷贝
# copyfile(src, dst)
# move()函数实现文件的剪切
# move(src, dst)

import shutil

shutil.copyfile("hello.py", "hello2.py")  #hello.txt内容复制给hello2.txt
shutil.move("hello.py", "../")       #hello.txt复制到当前目录的父目录,然后删除hello.txt
shutil.move("hell2.txt", "hello3.txt")   #hello2.txt移到当前目录并命名为hello3.py, 然后删除hello2.txt

来源:http://blog.csdn.net/henryghx/article/details/49227345

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com