python之文件的复制
1 2 3 4 5 6 7 8 | import os old_file_name = input ( "Please input what's file do you want to copy go:" ) fp = open (old_file_name) content = fp.read() index = old_file_name.rfind( '.' ) new_file_name = old_file_name[:index] + "[复件]" + old_file_name[index:] dp = open (new_file_name, 'w' ) dp.write(content) |
上面代码是文件的复制,我们的思路是这样的:
你可以打开一个存在的文件,然后去读取这个文件的内容,然后去创建一个新的文件,这个文件的名字是旧文件名字后面加上[复件]这样的字体。然后把我们刚刚在旧文件中读到的内容写到新文件里面去。关闭两个文件就好啦。
第二行让用户输入你想复制的文件,这个文件必须存在,而且最好是绝对路径。
第四行是打开我们要旧文件,用content变量是保存旧文件里面的内容
第五行去查找old_file_name这个变量的字符串中最右边出现的一个'.'符号的下标。
第六行是给new文件命名,然后赋予给变量new_file_name这个变量啊
那么上面有一个问题,如果说我们要复制一个你不知多大的文件的时候,千万不要用read,因为read会把所有的内容都读进内存,如果这个文件很大你的内存就崩了,也不要用readlines因为如果你的文件内容只有一行,这一行的数据很大,那你的内存也会被影响到。
可以用下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import os old_file_name = input ( "Please input what's file do you want to copy go:" ) fp = open (old_file_name) index = old_file_name.rfind( '.' ) new_file_name = old_file_name[:index] + "[复件]" + old_file_name[index:] dp = open (new_file_name, 'w' ) while True : content = fp.read( 1024 ) if len (content) = = 0 : break dp.write(content) fp.close() dp.close() |
上面代码的第8行是读这个文件的前1024个字符,然后再去判断读出来的内容是不是为空的,如果是的话就break退出循环,如果不是就就把内容写入新文件中

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
SpringBoot_异常_01_Caused by: java.lang.BootstrapMethodError: java.lang....
一、异常信息 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gsonBuilder' defined in class path resource [org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.gson.GsonBuilder]: Factory method 'gsonBuilder' threw exception; nested exception is java.lang.BootstrapMethodError: java.lang.NoSuc...
- 下一篇
java 代码混淆 proguard exception
错误信息 [DEBUG] (f) classpathElements = [D:\cache\git-repos\showandshare\showandshare\showandshare.gateway\showandshare.gateway.netty.dispacther\target\test-classes, D:\cache\git-repos\showandshare\showandshare\showandshare.gateway\showandshare.gateway.netty.dispacther\target\classes, F:\repository\repository\org\springframework\boot\spring-boot-starter-web\1.5.8.RELEASE\spring-boot-starter-web-1.5.8.RELEASE.jar, F:\repository\repository\org\springframework\boot\spring-boot-starter\1.5.8.RELEASE\sp...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- Linux系统CentOS6、CentOS7手动修改IP地址
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- CentOS6,CentOS7官方镜像安装Oracle11G
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- 设置Eclipse缩进为4个空格,增强代码规范
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程
- SpringBoot2配置默认Tomcat设置,开启更多高级功能