1 回答

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 个字节可能会引起质疑
添加回答
举报