現在讓我們再學習幾種文件操作。我們將編寫一個 Python 腳本,將一個文件中的內容拷貝到另外一個文件中。這個腳本很短,不過它會讓你對于文件操作有更多的了解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | from sys import argv
from os.path import 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 too, how?
input = open(from_file)
indata = input.read()
print "The input file 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()
|
你應該很快注意到了我們 import 了又一個很好用的命令 exists。這個命令將文件名字符串作為參數,如果文件存在的話,它將返回 True,否則將返回 False。在本書的下半部分,我們將使用這個函數做很多的事情,不過現在你應該學會怎樣通過 import 調用它。
通過使用 import ,你可以在自己代碼中直接使用其他更厲害的(通常是這樣,不過也不 盡然)程序員寫的大量免費代碼,這樣你就不需要重寫一遍了。
和你前面寫的腳本一樣,運行該腳本需要兩個參數,一個是待拷貝的文件,一個是要拷貝至的文件。如果我們使用以前的 test.txt 我們將看到如下的結果:
$ python ex17.py test.txt copied.txt
Copying from test.txt to copied.txt
The input file is 81 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.
$ cat copied.txt
To all the people out there.
I say I don't like my hair.
I need to shave it off.
$
該命令對于任何文件都應該是有效的。試試操作一些別的文件看看結果。不過小心別把你的重要文件給弄壞了。
Warning
你看到我用 cat 這個命令了吧?它只能在 Linux 和 OSX 下面使用,使用 Windows 的就只好跟你說聲抱歉了。