pythonlarge-datalarge-data-volumesdata-management

Add delimiters while writing into a text file


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!


Solution

  • 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