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

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

本文实例主要实现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

标签:python,复制文件
0
投稿

猜你喜欢

  • Gradio机器学习模型快速部署工具quickstart前篇

    2023-07-01 15:07:51
  • Python统计可散列的对象之容器Counter详解

    2023-09-23 18:30:50
  • php ZipArchive解压缩实现后台管理升级问题详解

    2023-05-25 11:58:10
  • python微信跳一跳系列之棋子定位颜色识别

    2023-01-16 04:52:49
  • php开发微信支付获取用户地址

    2023-09-07 15:12:08
  • 详解numpy.ndarray.reshape()函数的参数问题

    2022-02-06 20:22:57
  • MySQL转义字符的实际应用

    2010-08-31 14:55:00
  • Python+unittest+requests+excel实现接口自动化测试框架

    2021-09-08 07:04:49
  • python Requsets下载开源网站的代码(带索引 数据)

    2023-01-03 13:19:11
  • 在Python中使用判断语句和循环的教程

    2022-06-03 22:31:27
  • Python中的Selenium异常处理

    2021-08-28 04:15:23
  • python学习之列表的运用

    2023-08-02 03:11:30
  • Python实现ATM系统

    2021-10-17 05:20:46
  • 10个糟糕的IE Bug及其修复

    2010-05-13 16:26:00
  • Python字体反爬实战案例分享

    2021-06-18 01:00:46
  • python wsgiref源码解析

    2023-10-20 10:56:27
  • python实现单张图像拼接与批量图片拼接

    2023-07-28 12:33:36
  • 详解Python with/as使用说明

    2022-10-29 08:01:26
  • Oracle误添加数据文件删除方法

    2009-07-02 12:21:00
  • 什么是 XML Web Service

    2008-09-05 17:21:00
  • asp之家 网络编程 m.aspxhome.com