您的位置:首页 > 其它

练习17——更多文件操作

2016-07-01 14:35 239 查看
# -*- coding: utf-8 -*-
#更多文件操作——从A读取数据写入到B

#从自带库中导入argv和exists函数
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print ("Coping from %s to %s" % (from_file, to_file))

#打开文件from_file
my_input = open(from_file)
#给indata赋值为输入文件的数据
indata = my_input.read()

#len函数用来判断数据的大小
print ("The input file is %d bytes long." % len(indata))

#exists函数用来判断文件是否存在
print ("Does the output file exists? %r\nReady ,hit Return to continue, Ctrl-C to abort"
% exists(to_file))

#这边用输入作为程序的停顿,以后可能会有更好的办法
input()

my_output = open(to_file, 'w')
my_output.write(indata)

print ("Alright, all done.")

#最后不忘关文件。
my_input.close()
my_output.close()

#进阶问题1:这个脚本 实在是 有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。
#试着删掉脚本的一些功能,让它使用起来更加友好。
from sys import argv

script, from_file, to_file = argv

print ("Coping from %s to %s" % (from_file, to_file))
my_input = open(from_file)
indata = my_input.read()

my_output = open(to_file, 'w')
my_output.write(indata)
print ("Alright, all done.")
my_input.close()
my_output.close()

#进阶问题2:看看你能把这个脚本改多短,我可以把它写成一行。
#如下一行,可以实现功能。(不关闭文件可能会有问题,以后再想这个问题。)
open("C:/PE/FC2.txt", 'w').write(open("C:/PE/FC.txt").read())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: