1 回答

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ì)疑
添加回答
舉報(bào)