第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何使用 write() 從字符串中一次寫(xiě)入 x 個(gè)字節(jié)?

如何使用 write() 從字符串中一次寫(xiě)入 x 個(gè)字節(jié)?

慕妹3146593 2021-11-09 20:10:32
我正在為 Internet 模塊編寫(xiě)程序,該程序讀取本地存儲(chǔ)的文件,并將其寫(xiě)入我計(jì)算機(jī)上的 .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()我一口氣寫(xiě)完了整件事。問(wèn)題是當(dāng)產(chǎn)品被實(shí)現(xiàn)時(shí),一次只能寫(xiě)入 128 個(gè)字節(jié)。
查看完整描述

1 回答

?
HUWWW

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊

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


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字節(jié)x個(gè),直至碰到字符串的結(jié)尾,那么它將返回一個(gè)空字符串,這將終止while循環(huán)。


打開(kāi)和關(guān)閉文件的更簡(jiǎn)潔的方法是使用with關(guān)鍵字:



   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命令


注意:這是假設(shè)該readAll函數(shù)確實(shí)讀取了您提供的整個(gè)文件。一次只能讀取 128 個(gè)字節(jié)可能會(huì)引起質(zhì)疑


查看完整回答
反對(duì) 回復(fù) 2021-11-09
  • 1 回答
  • 0 關(guān)注
  • 238 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)