猿问

如何使用 write() 从字符串中一次写入 x 个字节?

我正在为 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 个字节。


慕妹3146593
浏览 213回答 1
1回答

HUWWW

要从流中写入,io模块在这里可以很好地提供帮助。我假设你不希望写字节文件,所以我们将使用StringIO对象,这将把一个字符串对象就像一个文件处理程序from io import StringIOdef 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 个字节可能会引起质疑
随时随地看视频慕课网APP

相关分类

Python
我要回答