为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 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 关注
  • 212 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信