Python: How to read csv file with different separators?
<p>This is the first line of my txt.file</p>

<pre><code>0.112296E+02-.121994E-010.158164E-030.158164E-030.000000E+000.340000E+030.328301E-010.000000E+00
</code></pre>

<p>There should be 8 columns, sometimes separated with '-', sometimes with '.'. It's very confusing, I just have to work with the file, I didn't generate it.</p>

<p>And second question: How can I work with the different columns? There is no header, so maybe:</p>

<p><code>df.iloc[:,0]</code> .. ? </p>

<p>As stated in comments, this is likely a list of numbers in scientific notation, that aren't separated by anything but simply glued together.
It could be interpreted as:</p>

<pre><code>0.112296E+02
-.121994E-010
.158164E-030
.158164E-030
.000000E+000
.340000E+030
.328301E-010
.000000E+00
</code></pre>

<p>or as </p>

<pre><code>0.112296E+02
-.121994E-01
0.158164E-03
0.158164E-03
0.000000E+00
0.340000E+03
0.328301E-01
0.000000E+00
</code></pre>

<p>Assuming the second interpretation is better, the trick is to split evenly every 12 characters.</p>

<pre><code>data = [line[i:i+12] for i in range(0, len(line), 12)]
</code></pre>

<p>If really the first interpretation is better, then I'd use a REGEX</p>

<pre><code>import re
line = '0.112296E+02-.121994E-010.158164E-030.158164E-030.000000E+000.340000E+030.328301E-010.000000E+00'
pattern = '[+-]?\d??\.\d+E[+-]\d+'
data = re.findall(pattern, line)
</code></pre>

<hr>

<p><strong>Edit</strong></p>

<p>Obviously, you'd need to iterate over each line in the file, and add it to your dataframe. This is a rather inefficient thing to do in Pandas. Therefore, if your preferred interpretation is the fixed width one, I'd go with @Ev. Kounis ' answer: <code>df = pd.read_fwf(myfile, widths=[12]*8)</code> </p>

<p>Otherwise, the inefficient way is:</p>

<pre><code>df = pd.DataFrame(columns=range(8))
with open(myfile, 'r') as f_in:
    for i, lines in enumerate(f_in):
        data = re.findall(pattern, line)
        df.loc[i] = [float(d) for d in data]
</code></pre>

<p>The two things to notice here is that the DataFrame must be initialized with column names (here [0, 1, 2, 3..7] but perhaps you know of better identifiers); and that the regex gave us strings that must be casted to floats.</p>

python csv pandas