python 筆記 文件內容的拷貝 (《笨辦法學Python》習題17)——12.26

習題 17:更多文件操作

目標與感悟:

 

•複製文本內容至其他文件中

 

ex17.py

#-*-coding: utf-8-*-
from sys import argv
 
'''
此處引用了新的內置函數,exists函數是檢查括號內字符串所代表的文件名的文件是否存在,
存在返回True,不存在返回False。
os.path os.path模塊主要用於文件的屬性獲取,在編程中經常用到
'''
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()
 
#len(),則是用於傳遞字符串的長度。
print "The input file is %d bytes long" %len(indata)
 
#此處使用exists驗證新文件是否已經存在。
print"Does the output file exist? %r" % exists(to_file)
print"Ready, hit RETURN to continue,CTRL-C to abort."
 
#此處的raw_input()我還是不是特別理解,只知道大概是詢問下一步是否繼續。稍後做個簡化測試。
raw_input()
 
#將open函數得到的結果(是一個文件,而不是文件的內容)賦值給in_file。
out_file = open(to_file, 'w')
 
#使用read函數讀取文件內容,並將文件內容賦值給indata。
out_file.write(indata)
 
print "Alright, all done."
 
#最後保存關閉。
out_file.close()
in_file.close()


運行結果:

•很明顯看出不同來了,對比2次運行結果,通過exists(to_file)來進行了一次判定,因爲第一次運行時候文件不存在,所以第一次是false,第二次是true



感悟與自我測試:

自己參照原文,簡化寫個腳本吧。

ex17_1.py

#-*-coding:utf-8-*-
from sys import argv
from os.path import exists
 
script, from_file,to_file = argv
 
print"Copy,from %r to %r" %(from_file,to_file)
 
in_file = open(from_file)
read_file = in_file.read()
 
print "%d" %len(read_file)
print "Is exist? %r" %exists(to_file)
 
raw_input("Continue?")
 
out_file = open(to_file,'w')
out_file.write(read_file)    
 
print "Allright!"
out_file.close()
in_file.close()    
'''
總結下最關鍵的4個句子:
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')
out_file.write(read_file)
 
翻譯過來就是:
打開源文件
讀取源文件
打開/新建目標文件
寫入目標文件
 
'''

運行結果:




是的,看起來還不夠簡潔,讓我們來個最不友好的簡單腳本。

 

ex17_2.py

#-*-coding:utf-8-*-
 
from sys import argv
script, from_file,to_file = argv
 
 
in_file = open(from_file)
read_file = in_file.read()
out_file = open(to_file,'w')

out_file.write(read_file)

運行結果:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章