Yelena Randall
Yelena Randall

Reputation: 11

CSV writer displays each character in separate columns

I have a .txt file with coordinates and earthquake magnitudes. I need to extract only 3 of the columns (latitude, longitude and magnitude) but the loadtxt in numpy module is not working. I wanted to convert the txt file into a csv file to see if I can extract the data I need... Here is what I have now. It returns a .csv file with each character printed as a separate row.

import csv 

s = open('Sismos_24_4_17.txt',"r").read()
print(s)

sc = open('Sismos_24_4_17.csv',"rt")

in_txt = csv.reader(s, delimiter = '\t')

out_csv = csv.writer(open('Sismos_24_4_17.csv',"wt"))

out_csv.writerows([in_txt])

print(sc.read())

Here are a few lines of the .txt file:

Local   Fecha   Latitud     Longitud    Profundidad Magnitud    Referencia
24/04/2017 20:58:01 24/04/2017 23:58:01 -33.307     -71.769     20.6    4.3 Ml GUC  19 km al NO de El Tabo
24/04/2017 20:54:45 24/04/2017 23:54:45 -33.292     -71.934     28.4    4.6 Mw GUC  31 km al NO de El Tabo
24/04/2017 20:47:29 24/04/2017 23:47:29 -32.985     -72.008     25.8    3.2 Ml GUC  37 km al O de Valparaíso

And here are a few lines of the .csv file my code creates:

['L'],['o'],['c'],['a'],['l'],"['', '']",['F'],['e'],['c'],['h'],['a'],"['', '']",['L'],['a'],['t'],['i'],['t'],['u'],['d'],"['', '']","['', '']",['L'],['o'],['n'],['g'],['i'],['t'],['u'],['d'],"['', '']",['P'],['r'],['o'],['f'],['u'],['n'],['d'],['i'],['d'],['a'],['d'],"['', '']",['M'],['a'],['g'],['n'],['i'],['t'],['u'],['d'],"['', '']",['R'],['e'],['f'],['e'],['r'],['e'],['n'],['c'],['i'],['a'],[],['2'],['4'],['/'],['0'],['4'],['/'],['2'],['0'],['1'],['7'],[' '],['2'],['0'],[':'],['5'],['8'],[':'],['0'],['1'],"['', '']",['2'],['4'],['/'],['0'],['4'],['/'],['2'],['0'],['1'],['7'],[' '],['2'],['3'],[':'],['5'],['8'],[':'],['0'],['1']

How can I get it to separate each element with a comma!

Upvotes: 1

Views: 562

Answers (2)

Reiko
Reiko

Reputation: 1

You should add quoting to the csv.reader. I don't know why but for the first time when I was reading file via csv module the same occurred to me after adding the quoting to the csv.reader all is good

in_txt = csv.reader(s, delimiter = '\t', quoting=csv.QUOTE_NONE)
out_csv = csv.writer(open('Sismos_24_4_17.csv',"wt"), quoting=csv.QUOTE_NONE)

Worked for me try experimenting with it check the man page for csv library

Upvotes: 0

cs95
cs95

Reputation: 403128

You're not extracting the first 3 columns like you should. I'd recommend iterating over each line in the input, and concurrently writing to the out-file. You can use the with...as context manager to make this easy.

with open('Sismos_24_4_17.csv', "rt") as i, open('Sismos_24_4_17_2.csv', "wt") as o:
    r = csv.reader(i, delimiter='\t')
    w = csv.writer(o)
    for row in r:
        w.writerow(row[:3])

What's more, you should write your output to a separate file, with a different name.

Upvotes: 1

Related Questions