Reputation: 43
I try to edit one of the column data into the format I want by using csv.DictReader()
, the code is like this:
import csv
import time
with open('201701.csv') as inf:
reader = csv.DictReader(inf)
for row in reader:
date = row['日期']
d = date.split('/')
year = int(d[0]) + 1911
month = str(d[1])
day = str(d[2])
date_ = str(year) + "{0:2}".format(month) + "{0:2}".format(day)
print(date_)
the outcome is like this:
20170103
20170104
20170105
20170106
20170109
20170110
20170111
20170112
20170113
20170116
20170117
20170118
20170119
20170120
20170123
20170124
But I want the data in the way like this:
date_list = ['20170103', '20170104', '20170105', '20170106', '20170109', '20170110', '20170111', '20170112', '20170113', '20170116', '20170117', '20170118', '20170119', '20170120', '20170123', '20170124']
Upvotes: 1
Views: 88
Reputation: 87134
You could write it as a generator. This gives you the ability to iterate over the sequence of dates from the file, or collect them together in a list. I have simplified your code :
import csv
import time
def get_dates(inf):
for row in csv.DictReader(inf):
year, month, day = row['日期'].split('/')
yield '{}{:02}{:02}'.format(int(year) + 1911, int(month), int(day))
Usage:
# Collect into a list
with open('201701.csv') as inf:
date_list = list(get_dates(inf))
print(date_list)
# Or iterate over the dates
with open('201701.csv') as inf:
for date in get_dates(inf):
print(date)
Upvotes: 1
Reputation: 3785
Well, if you want a date_list
then you should make one!
import csv
import time
date_list = []
with open('201701.csv') as inf:with open('201701.csv') as inf:
reader = csv.DictReader(inf)
for row in reader:
date = row['日期']
d = date.split('/')
year = int(d[0]) + 1911
month = str(d[1])
day = str(d[2])
date_ = str(year) + "{0:2}".format(month) + "{0:2}".format(day)
print(date_)
date_list.append(date_)
print(date_list)
Upvotes: 0
Reputation: 3301
Your output is like that because you print a single string date using print(date_)
iteratively. That is not a list at all.
To make a list, append your date string to a list date_list
:
import csv
import time
date_list = [] # create list of date
with open('201701.csv') as inf:with open('201701.csv') as inf:
reader = csv.DictReader(inf)
for row in reader:
date = row['日期']
d = date.split('/')
year = int(d[0]) + 1911
month = str(d[1])
day = str(d[2])
date_ = str(year) + "{0:2}".format(month) + "{0:2}".format(day)
date_list.append(date_) # append your date string to list
print(date_list)
Upvotes: 1