-1

I am writing an array into the text file, which I later use to read in excel for plotting. The data file is split in such a way that after 1000000 steps (approximately), the file closes and starts writing to another file.

However, my text file is writing data as a big chunk of values without any separators. Please refer the code below and let me know where I am going wrong.

counter = 1
for i in range(0, len(abc_value), 1000000):
    with open(f"abc{counter}.txt", "w") as file:
        for val in abc_value[i:i + 1000000]:
            file.write(str(val))
        file.close()
        counter += 1

Thank you!

user1234
  • 257
  • 2
  • 13

2 Answers2

1

Please see example below for using csv writer.

import csv
with open('abc.txt', 'w') as csv_file:
    wrtr = csv.writer(csv_file)
    for val in range(10):
        wrtr.writerow(str(val))
                                   
lllrnr101
  • 2,288
  • 2
  • 4
  • 15
1

The idea is correct but you are reading the values ​​of the array and they do not have a comma. You have to add the comma when passing the value to string. A simple way to do it would be:

counter = 1
for i in range(0, len(abc_value), 1000000):
    with open(f"hola.txt", "w") as file:
        file.write(str(abc_value[i]))
        for val in abc_value[i+1:i + 1000000]:
            file.write(", " + str(val))
        file.close()
        counter += 1
Jose Manuel de Frutos
  • 1,040
  • 1
  • 7
  • 19