我需要帮助从文本文件中导入这样的数据:
Orville Wright 1988年7月21日
Rogelio Holloway 1988年9月13日
Marjorie Figueroa 1988年10月9日
并将其显示在python shell上,如下所示:
名称
出生日期
答案 0 :(得分:-1)
将文件行读入列表 In Python, how do I read a file line-by-line into a list?
枚举 https://docs.python.org/2.3/whatsnew/section-enumerate.html
with open('filename') as f:
lines = f.readlines() # see above link
names = [] # list of 2-element lists to store names
timestamps = [] # list of 3-element lists to store timestamps as day/month/year
# preprocess
for line in lines:
a = line.split(" ") # the delimiter you use appears to be a space
names.append(a[:2]) # everything up to and excluding third item after split
timestamps.append(a[2:]) # everything else
# output
print("some header here") # put whatever you want here
for i, name in enumerate(names): # see enumeration reference
# you could add a length check on name[0] in case first name is blank
print("{}. {}. {}".format(str(i+1), name[0][0], name[1]))
print("another header here") # again use whatever header you want here
for i, timestamp in enumerate(timestamps):
print("{}. {}".format(str(i+1), " ".join(timestamp))