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

Time:10-12

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

CodePudding user response:

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.

CodePudding user response:

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