How to read an input file in Python and convert to an array

Viewed 59

I have an input file with the format: .in The file is following:

%     x           R     delta     Uc   
   0.9800000   0.4040404   0.1306061   1.0000000
   1.9800000   0.3393939   0.2311111   1.0000000
   2.9800000   0.2585859   0.3517172   0.9924242
   3.9800000   0.1696970   0.4723232   0.9924242
   4.9800000   0.0808081   0.5929293   0.9924242
   5.9800000   0.0000000   0.7135354   0.9696970
6.9800000   0.0000000   0.7738384   0.9015152
7.9800000   0.0000000   0.8341414   0.8333333
8.9800000   0.0000000   0.9145455   0.7575758
10      0       1.0133      .7064
11      0       1.1105      .6654
12      0       1.2077      .6312
13      0       1.3049      .6023
14      0       1.4021      .5775
15      0       1.4993      .5561
16      0       1.5965      .5373
17      0       1.6937      .5207
18      0       1.7909      .5060
19      0       1.8881      .4928

How can I put this information in an array like:

x = [0.980000, 1.980000, 2.980000 .....]
R = [0.40404,  0.33939,  0.231111 .....]
delta = ....
Uc = ....
2 Answers

This is a simple way to do it:

import pandas
df=pd.read_csv('your_file.in', sep=' ')
for i in df.columns:
    i=list(df[i])

This layout seems to be easily parseable with Python's csv module.

import csv

with open("file.in") as file:
    data = csv.reader(file, delimiter=" ", skipinitialspace=True)

    x, R, delta, Uc = zip(*data)

No dependencies needed!

Related