简体   繁体   中英

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

I have array of this integer type:

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:

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:

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.

You should create a string list from your integer list.

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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