原文鏈接:http://learnpythonthehardway.org/book/ex17.html
現在讓我們做更多關於文件的操作練習。我們打算寫一個Python 腳本來實現將一個文件的內容複製到另一個文件中。這次腳本程序雖然非常簡短,但是它將會給你對文件操作有一些額外的想法。
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?
in_file = open(from_file)
indata = in_file.read()
print "The input file is %d bytes long" % len(indata)
print "Does the ouput file exist? %r" % exists(to_file)
print "Ready ,hit RETURN to continue ,CTRL-C to abort."
raw_input()
out_file = open(to_file ,'w')
out_file.write(indata)
print "Alright ,all done."
out_file.close()
in_file.close()
你應該立即可以注意到我們又用 import導入了一個很好用的 exists 命令。如果exists 函數中作爲參數的那個字符串所代表的文件存在的話,那麼它就返回 True值,否則就返回False 。我們在這本書的下半部分都將使用到這個函數來做很多事情,不過你現在你應該學會如何用import導入它。使用import你就可以使用很多其他程序員寫好的免費的更好的(額,一般來說都是更好的)的代碼,這樣你就不用再去寫那些代碼了。
輸出結果如下:
c:\>python ex17.py test.txt new_file.txt
Copying from test.txt to new_file.txt
The input file is 46 bytes long
Does the ouput file exist? True
Ready ,hit RETURN to continue ,CTRL-C to abort.
Alright ,all done.
這個程序應該適合對任何文件操作。你可以嘗試更多類似操作看看會發生什麼。研究訓練:
1、去閱讀關於Python import 的介紹文檔,並且啓動Python體驗一下import的用法。試着導入一些東西看看你是否能正確使用它。如果你不能正確使用也沒有關係。open(raw_input("To File name:") ,'w').write(open(raw_input("From file name:")).read())