简体   繁体   English

如何将数组(整数)保存到 Python 中的文本文件?

[英]How to save array (integer) to text file in Python?

I have array of this integer type:我有这个 integer 类型的数组:

object = [[6, 0, 2, 3, 5, 0], [0, 2, 1, 0, 3, 2], [6, 0, 1, 0, 4, 1], [6, 1, 1, 0, 3, 2], [6, 2, 1, 2, 1, 2]]

How can I save this to an xyz.txt file in this format with 5 lines:如何将其保存到 xyz.txt 文件中,格式为 5 行:

6 0 2 3 5 0 
0 2 1 0 3 2
6 0 1 0 4 1 
6 1 1 0 3 2 
6 2 1 2 1 2

The following code returns the error以下代码返回错误

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        txt_file.write(" ".join(line) + "\n")
TypeError: sequence item 0: expected str instance, int found

Use map to convert the nested lists to lists of strings:使用map将嵌套列表转换为字符串列表:

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        txt_file.write(" ".join(map(str, line)) + "\n")

As a side note, naming your variable object (or any other keyword of the language) is a bad habit.附带说明一下,将变量命名为object (或该语言的任何其他关键字)是一个坏习惯。

You should create a string list from your integer list.您应该从 integer 列表中创建一个字符串列表。

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        line_str = [str(n) for n in line] # create string list from integer list
        txt_file.write(" ".join(line_str) + "\n")

or you can do it by this way,或者你可以通过这种方式来做,

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        txt_file.write(" ".join([str(n) for n in line]) + "\n")

Another way is create a string from your integer list and write that string into your file另一种方法是从您的 integer 列表创建一个字符串并将该字符串写入您的文件

with open('xyz.txt', 'w') as txt_file:
    for line in object:
        string_line = ''
        for n in line:
            string_line += f"{n} "
        txt_file.write(string_line.strip() + "\n")

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

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