I need to read a csv
file (named CityPop.csv
) and this is the code I have:
import csv
with open ('CityPop.csv', 'r') as f:
read_data = f.read()
for line in f:
record=line.strip().split(",")
print read_data
f.close()
But when I try to run it, nothing is output.
I am not sure how to continue; this only leads into more advanced tasks I need to complete, which is difficult if I can't even figure this out.
Try this code
import csv
with open ('CityPop.csv', 'r') as f:
reader = csv.reader(f, delimiter=",")
#read_data = f.read()
for line in reader:
print(line)
#record=line.strip().split(",")
#print (read_data)
f.close()
EDIT As Ralf said " f.close()
is not necessary when using a with block"
An easier way of reading csv files using pandas library -
import pandas
df = pandas.read_csv('CityPop.csv')
print(df)
or you can try modifying your code as below -
import csv
with open ('CityPop.csv', 'r') as f:
read_data = csv.reader(f,delimiter=',')
for row in read_data:
print(row)
You have imported the csv module but never used it. So try read_data = csv.reader(f)
.
I suggest you follow the example from the docs of the python csv
module :
import csv
with open('CityPop.csv') as f:
csv_reader = csv.reader(f, delimiter=', ')
for row in csv_reader:
print ', '.join(row)
Analizing your code, there are a few issues:
f.close()
if you use a with
statement, the file will be closed automatically when exiting the with
block with
block, as the variable read_data
is defined inside it read_data
( for line in read_data:
), because you already used f.read()
so that iterating over f
will no yield anything record
each time, so I don't know why you want to it that way import csv
with open('CityPro.cvs') as f:
r = csv.reader(f, delimiter=',')
for line in r:
print(line)
f.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.