Python split lines from read file and write them with another format in another file
<p>I read the lines from a file which containing two columns with values in that style:</p>

<pre><code>      100.E-03             5.65581E-06
      110.E-03            11.222E-06  
      120.E-03            18.3487E-06 
      130.E-03            15.6892E-06 
</code></pre>

<p>I need to write them in antoher file as:</p>

<pre><code>          100.E-03       ,      5.65581E-06
          110.E-03       ,     11.222E-06  
          120.E-03       ,     18.3487E-06 
          130.E-03       ,     15.6892E-06 
</code></pre>

<p>Can I do this with split? Can I define spaces, for example 5 spaces as the split variable? And when yes, how can I pick the splitted parts in order to write them in the way I want:
My script looks like:</p>

<pre><code>for k in files:
    print 'k =',k
    from  abaqus import session
    print k 
    with open("niffacc{k}.inp".format(k=k)) as f1:
       with open("niffacc_{k}.inp".format(k=k),"w") as f2:
            for line in itertools.islice(f1, 4, None):
                b = line.split("            ")
                #print "b:", b
                c = b[1]
                d = b[3] 
                f2.write('%s'%c + "," + '%s'%d)    
    #with open('VY_{k}'.format(k=k), 'a') as f1:
    #lines = f1.readlines()
    f2.close()
    f1.close()
</code></pre>

<p>I think the problem is in defining b, the splitted line. Is there any problem by defining as split character the spaces? Does python have a problem ti split because of the many spaces or it is handled as a groups of spaces?
Is a better solution to convert the file in csv file and then back to txt file? </p>

<p>I'm not sure why you want that many spaces between your columns but you can just split on whitespace:</p>

<pre><code>with open('file1.txt') as f1, open('file2.txt', 'w') as f2:
    for line in f1:
        f2.write(line.split()[0] + ',' + line.split()[1] + '\n')
</code></pre>

<p>If you really want a bunch of spaces, then just use:</p>

<pre><code>f2.write(line.split()[0] + '    ,    ' + line.split()[1] + '\n')
</code></pre>

python csv split pick