python复制文件的代码_python 复制文件流程

例子代码:

[root@master script]#vim copy_file.py#!/usr/bin/python#-*- coding:utf-8 -*-

old_file_name= raw_input("Please input you need copy's file name:")

old_file= open(old_file_name,'r')

new_file= open('langwang.txt','w')

content=old_file.read()

new_file.write(content)

old_file.close()

new_file.close()

如果:hello.py  hello[复件].py 怎么实现呢?

[root@master script]#vim copy_file.py#!/usr/bin/python#-*- coding:utf-8 -*-

old_file_name= raw_input("Please input you need copy's file name:")

old_file= open(old_file_name,'r')

new_file_name= old_file_name.split('.')[0] + '[复件].' + old_file_name.split('.')[1]

new_file= open(new_file_name,'w')

content=old_file.read()

new_file.write(content)

old_file.close()

new_file.close()

还可以是:

[root@master script]#vim copy_file.py#!/usr/bin/python#-*- coding:utf-8 -*-

old_file_name= raw_input("Please input you need copy's file name:")

old_file= open(old_file_name,'r')#new_file_name = old_file_name.split('.')[0] + '[复件].' + old_file_name.split('.')[1]

position = old_file_name.rfind(".")

new_file_name= old_file_name[:position] + '[复件]' +old_file_name[position:]

new_file= open(new_file_name,'w')

content=old_file.read()

new_file.write(content)

old_file.close()

new_file.close()

提示:

当一个文件非常大的时候,禁止使用read()读取,内存空间有限,用read()读取大文件会出现memory err ,内存不足的情况

这种情况就没有解决办法吗?有的====》推荐使用如下代码:

[root@master script]#cat copy_file.py#!/usr/bin/python#-*- coding:utf-8 -*-

old_file_name= raw_input("Please input you need copy's file name:")

old_file= open(old_file_name,'r')

position= old_file_name.rfind(".")

new_file_name= old_file_name[:position] + '[复件]' +old_file_name[position:]

new_file= open(new_file_name,'w')whileTrue:

content= old_file.read(1024)if notcontent:breaknew_file.write(content)

old_file.close()

new_file.close()

##########文件的位置############

In [17]: f = open("hello.py",'r')

In [18]: f.read()

Out[18]: "#!/usr/bin/python\n#-*- coding:utf-8 -*-\n\ni = 1\n\nwhile i<=5:\n j = 1\n while j<=i:\n print '*',\n j+=1\n print ''\n i+=1\n\n"

In [19]: f.seek(0,0) ##指针,seek(0,0) 代表从头开始读

In [20]: f.read()

Out[20]: "#!/usr/bin/python\n#-*- coding:utf-8 -*-\n\ni = 1\n\nwhile i<=5:\n j = 1\n while j<=i:\n print '*',\n j+=1\n print ''\n i+=1\n\n"

In [21]: f.read()

Out[21]: ''

In [22]: f.tell() ##指针的位置索引

Out[22]: 141

In [23]: f.read()

Out[23]: ''

In [24]: f.tell()

Out[24]: 141

In [25]: f.seek(0,0)

In [26]: f.tell()

Out[26]: 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值