当然,鉴于replacement函数可能返回空字符串,不太建议这样直接使用,最好在前面先判断一下,或者放在try-except语句中。
作为代码例子,可能还没讲到异常处理这一章节,所以不完善是正常的。
#coding=utf-8records = []
record = {}
with open("data.txt") as f:
while True:
line = f.readline()
if not line:
if len(record)!= 0: records.append(record)
break
field = line[line.find(":") + 1:].strip()
if line.startswith("ScopeId"):
if len(record)!= 0: records.append(record)
record = {}
record["ScopeId"] = field
elif line.startswith("Name"):
record["Name"] = field
elif line.startswith("Free"):
record["Free"] = field
elif line.startswith("InUse"):
record["InUse"] = field
elif line.startswith("PercentageInUse"):
record["PercentageInUse"] = field
# 设置缺省项
for r in records:
r.setdefault("InUse", 0)
r.setdefault("PercentageInUse", 0)
r.setdefault("Name", "")
r.setdefault("Free", 0)
print records
假如你的5文件在同一个文件夹中,路径为pathfile_name_list = ['usa', 'china', 'uk', 'canada', 'japan']
data_list = []
for i in file_name_list:
data_list.append(pd.read_excel(path + '/%s.xlsx' % i))
data = pd.concat(data_list)