自定义函数:open_file_to_list(fname)实现功能:将文件内容读入,返回列表变量list
自定义函数:write_list_to_file(fname)实现功能:将列表变量list,保存到文件中
自定义函数:find_people(name,fname)实现功能:在文件中查询某人是否存在
自定义函数:delete_people(name,fname)实现功能:在文件中删除某人数据
自定义main()函数:调用相关函数,实现功能:将60岁以上人员删除,将更新后数据写入"新文件.csv"
参考代码:
import csv
def open_file_to_list(fname):
with open(fname,'r',encoding='utf-8') as f:
data=f.readlines()
return data
def write_list_to_file(fname1,data):
with open(fname1,'w',encoding='utf-8') as f1:
f1.writelines(data)
def find_people(name,data):
for x in data:
if name in x:
print('yes')
break
else:
print('no')
def delete_people(name,data):
for x in data:
if name==x.split(',')[0]:
data.remove(x)
return data
def main():
fn='fp1.txt'
d = open_file_to_list(fn)
d1=d.copy()
fn1='fp2.txt'
write_list_to_file(fn1,d)
find_people('abc',d)
delete_people('abc',d)
for b in d1:
if int(b.split(',')[1])>60:
d1.remove(b)
writer=csv.writer(open('新文件.csv','w',encoding='utf-8',newline=''))
items=[item.strip().split(',') for item in d1]
writer.writerows(items)
main()