簡體   English   中英

Python字符串和整數寫入文件?

[英]Python strings and integers to write to file?

我是Python的新手,所以不確定如何執行此操作。

我有要寫入文件的字符串列表。 每個字符串必須以等於該字符串長度的32位整數開頭。

我需要將所有要寫入文件的數據寫入文件中。 在C#中,我會在編寫之前將所有內容存儲在字節數組中,但是我不知道在Python中做什么。 我應該使用列表,還是有更好的數據類型? 信息應如何存儲?

編輯:它看起來像一個例子:

00 00 00 04 74 65 73 74

big endian中整數的四個字節,后跟字符串。

如果您將數據存儲在名為“ 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM