標籤:參數 輸出 分享圖片 define type 修改 時報 back 覆蓋
一:檔案儲存
def save_to_file(file_name, contents): fh = open(file_name, ‘w‘) fh.write(contents) fh.close()save_to_file(‘mobiles.txt‘, ‘your contents str‘)
結果:
將字串修改則覆蓋原來的字串
將字串用變數替代
將 fh = open(file_name, ‘w‘)寫的許可權去掉報錯:
fh.write(contents)
io.UnsupportedOperation: not writable
寫入權限不加引號報錯:
fh = open(file_name, w)
NameError: name ‘w‘ is not defined
def save_to_file(file_name):中少一個參數報錯:
save_to_file(‘mobiles.txt‘,data)
TypeError: save_to_file() takes 1 positional argument but 2 were given
def save_to_file(file_name,contents): fh = open(file_name, ‘w‘) fh.write(contents) fh.close() print(type(fh),fh)data=‘machangwei‘save_to_file(‘mobiles.txt‘,data)
列印結果:
<class ‘_io.TextIOWrapper‘> <_io.TextIOWrapper name=‘mobiles.txt‘ mode=‘w‘ encoding=‘cp936‘>
當data=123或列表、元組、字典等時報錯,必須是字串:
TypeError: write() argument must be str, not int
當其他類型想要輸出到檔案時需要變成字串:
Python雜篇