亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 write() 從字符串中一次寫入 x 個字節?

如何使用 write() 從字符串中一次寫入 x 個字節?

慕妹3146593 2021-11-09 20:10:32
我正在為 Internet 模塊編寫程序,該程序讀取本地存儲的文件,并將其寫入我計算機上的 .txt 文件。def write2file():    print "Listing local files ready for copying:"    listFiles()    print 'Enter name of file to copy:'    name = raw_input()    pastedFile = readAll('AT+URDFILE="' + name + '"')    #Reads a local file using AT commands (not important to discuss)    print 'Enter path to file directory'    path = raw_input()    myFile = open(join(path, name),"w")    myFile.write(pastedFile)    myFile.close()我一口氣寫完了整件事。問題是當產品被實現時,一次只能寫入 128 個字節。
查看完整描述

1 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

要從流中寫入,io模塊在這里可以很好地提供幫助。我假設你不希望寫字節文件,所以我們將使用StringIO對象,這將把一個字符串對象就像一個文件處理程序


from io import StringIO


def write2file(bytes_to_write):

    print "Listing local files ready for copying:"

    listFiles()

    print 'Enter name of file to copy:'

    name = raw_input()

    pastedFile = readAll('AT+URDFILE="' + name + '"')


    # I'm assuming pastedFile is a `string` object

    str_obj = StringIO(pastedFile)


    # Now we can read in specific bytes-sizes from str_obj

    fh = open(os.path.join(path, name), 'w')


    # read in the first bit, bytes_to_write is an int for number of bytes you want to read

    bit = str_obj.read(bytes_to_write)


    while bit:

        fh.write(bit)

        bit = str_obj.read(bytes_to_write)


    fh.close()

這種工作方式是StringIO將read字節x個,直至碰到字符串的結尾,那么它將返回一個空字符串,這將終止while循環。


打開和關閉文件的更簡潔的方法是使用with關鍵字:



   with open(filename, w) as fh:

       # read in the first bit, bytes_to_write is an int for number of bytes you want to read

       bit = str_obj.read(bytes_to_write)


       while bit:

           fh.write(bit)

           bit = str_obj.read(bytes_to_write)

這樣你就不需要顯式open和close命令


注意:這是假設該readAll函數確實讀取了您提供的整個文件。一次只能讀取 128 個字節可能會引起質疑


查看完整回答
反對 回復 2021-11-09
  • 1 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號