简体   繁体   中英

Append a 2D array to text file

What would be the best way to append a 2D array to a file after writing in the dimensions? Getting something like this:

5 6
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

I've tried using this:

with open(file_name, 'a+') as file:
    file.write(dimensions)
    file.append(array)

But get: "AttributeError: '_io.TextIOWrapper' object has no attribute 'append'"

You can sort of get the effect using this:

np.savetxt(file_name, array, fmt='%i', header=dimensions)

But the dimensions are written as a comment, with no option to change that seemingly.

File object does not have an .append function. You could write a function:

def append_to_file(array, file_name)
    with open(file_name, 'a+') as file:
        for el in array.shape:
            file.write(str(el))
        file.write('\n')

        for row in array:
            for el in row:
                file.write('{} '.format(el))
            file.write('\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