exercise 17 读取文件_2

来源:互联网 发布:办公笔记本电脑 知乎 编辑:程序博客网 时间:2024/05/01 10:09
源程序:
from sys import argv
from os.path import exists  ## 从os.path模块中导入exists

script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()         ## 打开from_file,并将内容存入indata中
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)   ##还未将数据读入out_file中 所以 不存在
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()   ##键入 RETURN 或者CTRL-C吗 选择继续或停止?
out_file = open(to_file, 'w')
out_file.write(indata)     ## 为什么不是to_file 呢
print "Alright, all done."
out_file.close()
in_file.close()  ##最后要关闭文件



命令行输出
$ echo "This is a test file." > test.txt  ##利用echo将“This is a test file,” 写入 test.txt文件


$ cat test.txt   ##显示test文件
This is a test file.
$
$ python ex17.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The input file is 21 bytes long    ## only 20 within. maybe space after .
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.

echo命令的用途是将后面的内容作为字符串显示出来
比如 echo hello,就显示hello;
比如 echo /etc/reslov.conf ,会显示/etc/reslov.conf
cat命令的用途是打印文件到屏幕上
想看一个文件的内容是什么,可以用cat,比如 cat/etc/reslov.conf,就显示出文件reslov.conf里具体的内容。

尽量短!
from sys import argv;
open(argv[2], 'w').write(open(argv[1]).read())




0 0
原创粉丝点击