习题 17: 更多文件操作
在文本编辑器中,编辑以下内容并保存到ex17.py文件中,同时在终端中运行该文件:
##-- coding: utf-8 --
#将Python的功能(其实叫模组modules)引入到脚本中
#argv就是所谓的”参数变量“,这个变量包含了你传递给Python的参数
from sys import argv
from os.path import exists
#将argv中的东西解包,将所有的参数依次赋予左边的变量名,
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do thest two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
执行结果:
$ vim ex17_from.txt # 输入I am from txt
$ vim ex17_to.txt # 输入I am to txt
$ python ex17.py ex17_from.txt ex17_to.txt
Copying from ex17_from.txt to ex17_to.txt
The input is 14 bytes long
Does the output file exist? True
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.
$ cat ex17_to.txt # 输出ex17_to.txt文件中的内容
I am from txt
加分习题
- 再多读读和import相关的材料,将python运行起来,试试这一条命令。试着看 看自己能不能摸出点门道,当然了,即使弄不明白也没关系。
- 这个脚本 实在是 有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么 多东西。试着删掉脚本的一些功能,让它使用起来更加友好。
input = open(from_file)
output = open(to_file, 'w')
output.write(input.read())
output.close()
input.close()
- 看看你能把这个脚本改多短,我可以把它写成一行。
open(to_file, 'w').write(open(from_file).read())
- 我使用了一个叫 cat 的东西,这个古老的命令的用处是将两个文件“连接(concatenate)”到一起,不过实际上它最大的用途是打印文件内容到屏幕上。你可以通过 man cat 命令了解到更多信息。
- 找出为什么你需要在代码中写 。
原因在于如果不写,则新复制的文件中是不会保存任何内容的。也就是没有保存(如同在 16 题 Zed 介绍的一样)
out_put = open(to_file, 'w') 执行时会创建 to_file 文件,但是没内容
out_put.write(indata) 执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。
只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率(特别在特大文件的时候)
参考博客:https://blog.csdn.net/aaazz47/article/details/79570531