ömer sarı ömer sarı - 3 months ago 10
Python Question

CSV file unread columns

l m trying to get data from CSV file and there are three column ("date",stations","pcp" ) including 41 years data set. l would like to get these data separately.

example dataset:

date stations pcp
1.01.1979 6 1.071
2.01.1979 6 5.909
3.01.1979 6 9.134
1.01.1979 5 1.229
2.01.1979 5 0.014
3.01.1979 5 3.241


when l run code , l got this output

date;stations;pcp None None
2.04.1979;6;0.0 None None
3.04.1979;6;0.0 None None
4.04.1979;6;0.35 None None
5.04.1979;5;0.003 None None


date field including all data but stations and pcp fields are "None"
how can l solve it?

here is my code

import csv
import numpy as np

with open('p2.csv') as csvfile:
reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=' ', quotechar='|')
for row in reader:
print(row["date"],row["stations"],row["pcp"])

Answer

Your input file (p2.csv):

date stations pcp
1.01.1979 6 1.071
2.01.1979 6 5.909
3.01.1979 6 9.134
1.01.1979 5 1.229
2.01.1979 5 0.014
3.01.1979 5 3.241

Your code:

import csv
import numpy as np

with open('p2.csv') as csvfile:
    reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=' ', quotechar='|')
    for row in reader:
       print(row["date"],row["stations"],row["pcp"])

Output:

date stations pcp
1.01.1979 6 1.071
2.01.1979 6 5.909
3.01.1979 6 9.134
1.01.1979 5 1.229
2.01.1979 5 0.014
3.01.1979 5 3.241

There is a serious problem with your input file. The delimter is not a single space, it's having multiple spaces.

Comments