笨辦法學習Python3.x 習題17


 
         
 1 from sys import argv
 2 from os.path import exists
 3 
 4 script, from_file, to_file = argv
 5 
 6 print("Copying from %s to %s" % (from_file, to_file))
 7 
 8 # open 打開只讀文本
 9 input_file = open(from_file)  # Python3.x 不要用input做變量名,變量名變更后,下方使用到的地方也要跟隨改變
10 # read讀取文本
11 indata = input_file.read()
12 
13 print("輸入的文件長度為:%d" % len(indata))
14 
15 print("輸出的文件是否存在?%r" % exists(to_file))
16 print("點擊回車Enter繼續下一步")
17 input()
18 
19 # 加‘w',以可寫權限打開文本
20 output = open(to_file, 'w')
21 # 寫入已讀取的文本
22 output.write(indata)
23 
24 print("完成復制")
25 
26 output.close()
27 input_file.close()

加分習題,縮短代碼,分兩部完成,理解最終實現一行代碼
第一步:
b = open(from_file)
# 讀,可以直接默認讀取已打開的文本
c = b.read()      # 這里把read分開寫為什么報錯??,要再定義一個變量
a = open(to_file, 'w')
# 寫,必須要給出要寫入的參數
a.write(c)

第二步:

open(to_file, 'w').write(open(from_file).read())

 

 

關於open的詳細解釋:

因為默認open只能讀取不能寫入,所以要寫入內容就必須加入’w’參數。

‘w’:以只寫模式打開。若文件存在,則會自動清空文件,然后重新創建;若文件不存在,則新建文件。使用這個模式必須要保證文件所在目錄存在,文件可以不存在。該模式下不能使用read*()方法

 


 
         

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM