So i'm takinf a Python Essentials course right now, and im trying to read a CSV file. Using the csv module, and csv.DictReader im looping through a csv, making a dictionary for each line, and adding that line to a list which gets returned to main.py. For some reason i can't figure out, the last line is added every time instead of a new line every time.
import csv
def read_file(f_name):
f = []
my_dict = {}
with open(f_name) as f_data:
for line in csv.DictReader(f_data):
print(dict(line))
my_dict.update(dict(line))
f.append(my_dict)
return f
def print_file(f):
for entry in f:
print(entry)
print('file name > weather.csv')
f_name = 'python/topicchallenge6b/weather.csv'
f = read_file(f_name)
print()
print_file(f)
from CSV:
"Temp","Press","Humidity"
1.1,55.5,22.2
3.3,4.4,6.6
8.8,99.9,7.7
All three entries are saved as 8.8,99.9,7.7 but printed properly as the different sets.
file name > weather.csv
{'Temp': '1.1', 'Press': '55.5', 'Humidity': '22.2'}
{'Temp': '3.3', 'Press': '4.4', 'Humidity': '6.6'}
{'Temp': '8.8', 'Press': '99.9', 'Humidity': '7.7'}
{'Temp': '8.8', 'Press': '99.9', 'Humidity': '7.7'}
{'Temp': '8.8', 'Press': '99.9', 'Humidity': '7.7'}
{'Temp': '8.8', 'Press': '99.9', 'Humidity': '7.7'}
Why is python behaving like this, and is there a better way?