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

时间:2019-02-15 13:48:55

标签: python

我正在为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 个答案:

答案 0 :(得分:0)

要从流中写入内容,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()

此工作方式是StringIOread 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)

这样,您就不需要显式的openclose命令

注意: 假设readAll函数确实确实读取了您赋予它的整个文件。 一次只能读取128个字节可能会引起疑问