简体   繁体   中英

Writing a .txt file with different length arrays as columns

I am currently parsing some data from a simulation and would like to include all of it in a single.txt. The issue is that three of my data arrays are equal in length (about 140,000 datapoints each) while the 1st one, Ni_recoil is shorter (about 90,000 entries). When I write the file, the.txt is trimmed down to the length of the shortest array, in this case Ni_recoil. I would like to generate a.txt that contains all 4 columns of data without trimming down the longer arrays.

A simplified example of the output I get would be:

Ni_recoil = [1,2,3]    recoil = [1,2,3,4,5]    Energy = [1,2,3,4,5]    depth = [1,2,3,4,5]

Output: 1 1 1 1
        2 2 2 2
        3 3 3 3

What I would like to get is:

Output: 1 1 1 1
        2 2 2 2
        3 3 3 3
          4 4 4
          5 5 5

Here is my code for the writing section of the.txt

path=r"C:\Users\Jorge\Desktop\Uni\Research\JANUS\IIEE\Results\StainlessSteel_Xenon"
name_of_file = input("What is the name of the file: ")

completeName = os.path.join(path, name_of_file+".txt")
data=zip(Ni_recoil, recoil, energy, depth)

with open(completeName, 'w') as file:
    for(Ni_recoil, recoil, energy, depth) in data:
        file.write("{0},{1},{2},{3}\n".format(Ni_recoil, recoil, energy, depth))

Thank you in advance.

I tried tweaking the code several times and scouted the internet for solutions unsuccesfully

Try:

from itertools import zip_longest

Ni_recoil = [1, 2, 3]
recoil = [1, 2, 3, 4, 5]
Energy = [1, 2, 3, 4, 5]
depth = [1, 2, 3, 4, 5]

for data in zip_longest(Ni_recoil, recoil, Energy, depth, fillvalue=" "):
    print(*data, sep=" ")

Prints:

1 1 1 1
2 2 2 2
3 3 3 3
  4 4 4
  5 5 5

To write to a file:

from itertools import zip_longest

Ni_recoil = [1, 2, 3]
recoil = [1, 2, 3, 4, 5]
Energy = [1, 2, 3, 4, 5]
depth = [1, 2, 3, 4, 5]

with open("output.txt", "w") as f_out:
    for data in zip_longest(Ni_recoil, recoil, Energy, depth, fillvalue=" "):
        print(*data, file=f_out, sep=" ")

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