Reputation: 475
I have a file that has data that looks something like this:
1 1:-0.03125 2:0.236364 3:0.142857 4:-0.107438 5:0.129032 6:0.163636 7:0.242105
2 1:-0.03125 2:0.472727 3:0.761905 4:0.123967 6:0.472727 7:0.347368
....
Where there are a couple thousand lines total. I am trying to convert this over to a csv file.
I tried the following code:
with open("file1.test", "r") as infile:
with open("file1.csv", "w") as outfile:
for line in infile:
new_line = line
i = 1
for i in range(1,8):
to_replace = " " + str(i) + ":"
new_line = new_line.replace(to_replace, ",", 1)
new_line = line[:2] + "," + line[2:]
new_line = new_line.replace(" ", "", 1)
But it does not work as expected. The line new_line = new_line.replace(" ", "", 1)
works but when I am trying to replace the " 1:" with a comma it does not update. I want my final file to look like"
1, -0.03125,0.236364,0.142857,-0.107438,0.129032,0.163636,0.242105
2,-0.03125,0.472727,0.761905,0.123967,0.472727,0.347368
Any ideas what I am doing wrong?
Upvotes: 0
Views: 48
Reputation: 126
I like this
import re
with open("file1.test", "r") as infile:
with open("file1.csv", "w") as outfile:
for line in infile:
outfile.write(re.sub(' [1-7]:',',',line))
Upvotes: 1
Reputation: 23556
You may try this conversion approach for every line:
>>> a = '1 1:-0.03125 2:0.236364 3:0.142857 4:-0.107438 5:0.129032 6:0.163636 7:0.242105'
>>> ','.join( [i.split(':')[-1] for i in a.split()] )
'1,-0.03125,0.236364,0.142857,-0.107438,0.129032,0.163636,0.242105'
with your whole program looking like this:
with open("file1.test", "r") as infile:
text = [i.strip() for i in infile.readlines()]
output = []
for t in text :
output.append( ','.join( [i.split(':')[-1] for i in t.split()] ) )
with open("file1.csv", "w") as outfile:
outfile.write( '\n'.join( output ) )
Upvotes: 1