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

yipeiwu_com6年前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 

总结

以上就是本文关于浅谈Python实现2种文件复制的方法的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python使用matplotlib绘制折线图教程

python使用matplotlib绘制折线图教程

matplotlib简介 matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图。而且也可以方便地将它作为绘图控件,嵌入...

python实现简单ftp客户端的方法

本文实例讲述了python实现简单ftp客户端的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python # -*- coding: utf-8 -*- i...

python实现在windows下操作word的方法

本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下: import win32com from win32com.client...

python 魔法函数实例及解析

python的几个魔法函数 __repr__ Python中这个__repr__函数,对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串.如果我们直接打印...

Python3 使用pillow库生成随机验证码

Python3 使用pillow库生成随机验证码的代码如下所示: import random # pillow 包的使用 from PIL import Image,ImageDra...