简体   繁体   English

如何将列表写入文件?

[英]How do I write a list to a file?

how to write a list with elements with words from different languages and with numbers to a file?如何将包含来自不同语言的单词和数字的元素写入文件的列表?

s = ['привет', 'hi', 235, 235, 45]

with open('test.txt', 'wb') as f:
    f.write(s)

TypeError: a bytes-like object is required, not 'list'

Well since you are opening a .txt file and you mentioned different languages, I will assume that you want to write to a .txt file some values with different encoding.好吧,因为您正在打开一个.txt文件并且您提到了不同的语言,所以我假设您想将一些具有不同编码的值写入.txt文件。

( If that's not the case and you want to write binary, you can check the answers above ) 如果不是这种情况并且您想编写二进制文件,您可以查看上面的答案

You should specify the encoding for the file depending on the values you have.您应该根据您拥有的值指定文件的编码。

s = ['привет', 'hi', 235, 235, 45]

with open("filename.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(str(val) for val in s))
with open('filename.txt', 'w') as file:
    file.write(', '.join([str(item) for item in s]))

It writes every item in a list (first changing every item to a string of course) separated by a comma.它将每个项目写入列表中(当然首先将每个项目更改为字符串),并用逗号分隔。

Maybe convert (parse) to json string也许转换(解析)为 json 字符串
Like this:像这样:

import json

dataList = ["po", "op", "oo"]
dataJson = json.dumps(dataList)
# Then your code
# with open('test.txt', 'wb') as f: f.write(dataJson) 

Using 'wb' to open the file causes you to write in binary mode.使用'wb'打开文件会导致您以二进制模式写入。 I'm not sure if this is what you want, since you are writing to a .txt file.我不确定这是否是您想要的,因为您正在写入.txt文件。

If you are sure you want to write in binary mode, I would suggest you use .bin or .dat as the file extension for your file.如果您确定要以二进制模式编写,我建议您使用.bin.dat作为文件的文件扩展名。

If you are sure you want to write the output as binary, here is one way to do so (I make several assumptions here, because you don't give details in your question):如果您确定要将 output 编写为二进制文件,这是一种方法(我在这里做了几个假设,因为您没有在问题中提供详细信息):

import sys

s = ['привет', 'hi', 235, 235, 45]

# Create an empty bytearray
byte_array = bytearray()

# For each item in the list s, convert it to a bytearray, and append it to the
# output bytearray
for item in s:
    if isinstance(item, str):
        byte_array.extend(bytearray(item, 'utf-8'))
    elif isinstance(item, int):
        # Assumption: all ints in the list can be represented with only 2 bytes
        # Assumption: we want to output with the system's byte order
        byte_array.extend(item.to_bytes(2, sys.byteorder, signed=True))

# Here I use the .bin extension, because it is a binary file
with open('test.bin', 'wb') as f:
    f.write(byte_array)

If you instead do not want to write as binary, but want to write as text, see Spiros Gkogkas's answer .如果您不想写成二进制,而是想写成文本,请参阅Spiros Gkogkas 的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM