Python雜篇

來源:互聯網
上載者:User

標籤:參數   輸出   分享圖片   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雜篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.