我是 Python 新手,所以我不确定我应该怎么做。
我有一个要写入文件的字符串列表。每个字符串前面都需要一个等于字符串长度的 32 位整数。
在将其写入文件之前,我需要将所有要写入文件的数据。在 C# 中,我会在编写之前将所有内容存储在一个字节数组中,但我不知道在 Python 中该做什么。我应该使用列表,还是有更好的数据类型?信息应该如何存储?
编辑:它看起来像的一个例子是:
00 00 00 04 74 65 73 74
大端整数的四个字节,后跟字符串。
如果您的数据存储在名为“data”的列表中,并且您希望输出转到名为“data.out”的文件,则以下代码将完成此操作:
data = ['this', 'is', 'a', 'complicated and long', 'test']
with open('data.out', 'w') as outfp:
for d in data:
outfp.write('%4d %s\n' %(len(d), d))
产量:
4 this
2 is
1 a
20 complicated and long
4 test
作为文件“data.out”中的输出。请注意,%4d 中的 '4' 有助于将数字与前导空格对齐,以便输出格式很好。
或者,如果您想要字符的 ASCII 整数值:
with open('data.out', 'w') as outfp:
for d in data:
outfp.write('%4d %s\n' %(len(d), ' '.join([str(ord(i)) for i in d])))
你会得到
4 116 104 105 115
2 105 115
1 97
20 99 111 109 112 108 105 99 97 116 101 100 32 97 110 100 32 108 111 110 103
4 116 101 115 116
您可以使用 lambda 表达式根据字符串和格式要求轻松创建新列表,例如:
strings = ['abc', 'abcde', 'abcd', 'abcdefgh']
outputs = map(lambda x: "%d %s" % (len(x), x), strings) # ['3 abc', '5 abcde', '4 abcd', '8 abcdefgh']
f = open("file.out", 'w')
data = '\n'.join(outputs) # Concat all strings in list, separated by line break
f.write(data)
f.close()
根据您的要求,这将生成一个包含所有数据的大字符串:
>>> l = ["abc", "defg"]
>>> data = '\n'.join("%d %s" % (len(x), x) for x in l)
>>> data
3 abc
4 defg
然后将其写入文件,如下所示:
f = open("filename", "w")
f.write(data)
f.close()
假设您有一个存储在其中的字符串列表,list_of_strings
并且您打开了一个文件以写入file_handle
. 进行如下操作(未经测试)
for line in list_of_strings:
length_of_string = len(line)
line = str(length_of_string) + " " + line
file_handle.write(line)
字典是可以接受的。就像是:
strings = ['a', 'aa', 'aaa', 'aaaa'] #you'd get these
data = dict() #stores values to be written.
for string in strings:
length = len(string)
data.update({string: length})
#this is just a check, you would do something similar to write the values to a file.
for string, length in data.items():
print string, length
很抱歉造成混淆,我应该包括我需要整数字节的方式,而不仅仅是字符串之前的整数。
我最终得到了类似的东西:
import struct
output=''
mystr = 'testing str'
strlen = len(mystr)
output += struct.pack('>i',strlen) + mystr
将数据存储在列表中应该没问题。可以在编写文件时计算长度。棘手的部分是将它们编写为二进制而不是 ascii。
要处理二进制数据,您可能需要使用struct模块。它的 pack 功能将让您将字符串的长度转换为它们的二进制表示。由于它返回一个字符串,因此您可以轻松地将其与要输出的字符串组合。
下面的示例似乎适用于 Python 2.7
import struct
strings = ["a", "ab", "abc"]
with open("output.txt", "wb") as output:
for item in strings:
output.write("{0}{1}".format(struct.pack('>i', len(item)), item))