源程序:
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())