Python: Read a file into a List


File: weather_data.csv

Day,Temp (C),Humidity (%)
1,25,65
2,26,70
3,24,62
4,28,75
5,27,68
6,23,60
7,22,58
8,26,70
9,27,72
10,24,64

readfiletolist.py

import csv

weather_data = []

with open('weather_data.csv', 'r') as csvfile:
    csvreader = csv.DictReader(csvfile)
    for row in csvreader:
        weather_data.append({
            'Day': int(row['Day']),
            'Temp (C)': int(row['Temp (C)']),
            'Humidity (%)': int(row['Humidity (%)'])
        })

for data in weather_data:
    print(data)

Output:

% python3 readfiletolist.py 

{'Day': 1, 'Temp (C)': 25, 'Humidity (%)': 65}
{'Day': 2, 'Temp (C)': 26, 'Humidity (%)': 70}
{'Day': 3, 'Temp (C)': 24, 'Humidity (%)': 62}
{'Day': 4, 'Temp (C)': 28, 'Humidity (%)': 75}
{'Day': 5, 'Temp (C)': 27, 'Humidity (%)': 68}
{'Day': 6, 'Temp (C)': 23, 'Humidity (%)': 60}
{'Day': 7, 'Temp (C)': 22, 'Humidity (%)': 58}
{'Day': 8, 'Temp (C)': 26, 'Humidity (%)': 70}
{'Day': 9, 'Temp (C)': 27, 'Humidity (%)': 72}
{'Day': 10, 'Temp (C)': 24, 'Humidity (%)': 64}
Ptyhon Read File as List Example
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap