我尝试使用csv.DictReader()
将其中一个列数据编辑为我想要的格式,代码如下:
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_)
结果是这样的:
20170103
20170104
20170105
20170106
20170109
20170110
20170111
20170112
20170113
20170116
20170117
20170118
20170119
20170120
20170123
20170124
但我希望数据的方式如下:
date_list = ['20170103', '20170104', '20170105', '20170106', '20170109', '20170110', '20170111', '20170112', '20170113', '20170116', '20170117', '20170118', '20170119', '20170120', '20170123', '20170124']
答案 0 :(得分:1)
您的输出就是这样,因为您使用print(date_)
迭代地打印单个字符串日期。这根本不是一个清单。
要制作列表,请将日期字符串附加到列表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)
答案 1 :(得分:1)
您可以将其编写为生成器。这使您能够从文件中迭代日期序列,或者在列表中一起收集日期。我简化了你的代码:
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))
用法:
# 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)
答案 2 :(得分:0)
好吧,如果你想要date_list
那么你应该制作一个!
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)