JM9
JM9

Reputation: 119

how to replace multiple types of delimiters with a comma

I have the following string in a text file

SCF Done: E(RHF) = -100.055079426 A.U. after 9 cycles

The goal is to convert this string into csv type data by getting rid of all the unwanted white space and replacing it with commas. Here is what I have so far

import csv


f = open('testfile1','r')

x = f.readlines()

s = []

for line in x:

    line = line.strip(' ')

    line = line.replace('  ',',')

    s.append(line)

csvex = csv.writer(open('name.csv', "w"), quoting=csv.QUOTE_ALL)

csvex.writerow(s)

The code gives me the following output

"SCF Done:,E(RHF) =,-100.055079426,, A.U. after,,9 cycles
"

I want the code to give me the following output


"SCF,Done:,E(RHF),=,-100.055079426,A.U.,after,9,cycles"

How do I go about fixing this?

Upvotes: 1

Views: 453

Answers (2)

Rahul Joshi
Rahul Joshi

Reputation: 1

import csv

file = open("testfile1",'r')
x=file.readlines()

s=[]
for line in x:

    line = line.strip(' ')
    line = ",".join(line.split())
    s.append(line)

csvex = csv.writer(open("name.csv", "w"), quoting=csv.QUOTE_ALL)

csvex.writerow(s)

",".join(line.split()) is the function which splits and then insert ',' at every space

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195528

csvwriter.writerow accepts iterable (list, tuple, etc.) (doc).

This script read input file line by line, split the line and write the line to csv file.

If file.txt contains:

SCF Done:  E(RHF) =  -100.055079426     A.U. after    9 cycles

Then this script:

import csv

with open('file.csv', 'w') as f_out, \
    open('file.txt', 'r') as f_in:
    csvex = csv.writer(f_out, quoting=csv.QUOTE_MINIMAL)
    for line in f_in:
        csvex.writerow(line.strip().split())

Writes csv file file.csv with content like this:

SCF,Done:,E(RHF),=,-100.055079426,A.U.,after,9,cycles

Upvotes: 2

Related Questions