笨辦法學python17 更多檔案操作

2021-08-10 14:41:04 字數 1326 閱讀 9996

這個習題我們將學習到檔案操作的另外乙個庫 os.path和乙個新命令:exists(這個命令將檔名稱作為引數,如果檔案存在返回true,如果不存在返回false.同時新建此檔案)。

另外通過這個習題,我們對檔案的讀取、寫入會有更深的理解。

**如下:

#-*-coding:utf-8-*-

from sys import argv

from os.path import exists

script , from_file , to_file = argv

print"copy from %s to %s"%(from_file , to_file)

#we coule do these two on line too ,how?

in_file = open(from_file)

indata = in_file.read()

#以上兩句可以寫成一句:indata = open(from_file).read()

print"the input file is %d byte 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()

out_file = open(to_file , 'w')

out_file.write(indata)

print"alright,all done."

out_file.close()

in_file.close()

print"the contents of to_file is %r" %open(to_file).read()

在執行這個習題時,需要明確兩點:

1,open輸入時引數,返回的是object。所以如果open()括號裡面的內容不是檔名,而是物件時,執行會報錯

比如mark黃色部分若改為:

print"the contents of to_file is %r" %open(out_file).read()

報錯資訊如下:

print"the contents of to_file is %r" %open(out_file).read()

typeerror: coercing to unicode: need string or buffer, file found

2,read是物件的方法,所以其必須跟在乙個物件的後面。

《笨辦法學python》習題17 更多檔案操作

from sys import argv from os.path import exists 我們 import 了又乙個很好用的命令 exists。這個命令將檔名字串作為引數,如果檔案存在的話,它將返回 true,否則將返回 false。script,from file,to file argv...

《笨辦法學Python》 習題17 更多檔案操作

系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 1.完成基本習題 1.再多讀讀和import相關的材料,將python執行起來,試試這一條命令。試著看 看自己能不能摸出點門道,當然了,即使弄不明白也沒關係。2.這個指令碼 實在是 有點煩人。沒必要在拷貝...

笨辦法學python 習題17 更多檔案操作

檔案內容拷貝 從sys模組匯入ar 引數變數 from sys import ar 從os.path模組匯入exists 判斷檔案路徑 from os.path import exists 解包 from file和to file定義兩個檔名 script,from file,to file ar ...