用python第一步,生成一个字典,关键字包含年龄,姓名,性别。 第二步,生成三个字典,并把他们追加到列表中 第三步,把列表用open()写入到内存中; 第四步,设计一个修改模块,能够修改他们的年龄姓
第一步:生成一个字典,关键字包含年龄,姓名,性别。
```python
info = {"年龄": 0, "姓名": "", "性别": ""}
```
第二步:生成三个字典,并把他们追加到列表中。
```python
info_list = []
info1 = {"年龄": 25, "姓名": "张三", "性别": "男"}
info2 = {"年龄": 30, "姓名": "李四", "性别": "女"}
info3 = {"年龄": 22, "姓名": "王五", "性别": "男"}
info_list.append(info1)
info_list.append(info2)
info_list.append(info3)
```
第三步:把列表用open()写入到内存中。
```python
with open("info_list.txt", "w") as f:
for info in info_list:
f.write(str(info) + "
")
```
第四步:设计一个修改模块,能够修改他们的年龄姓名性别等。修改完后替换到内存中。
```python
def update_info(old_info, new_info):
old_info.update(new_info)
return old_info
def load_info_from_file(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
info_list = [eval(line.strip()) for line in lines]
return info_list
def save_info_to_file(file_path, info_list):
with open(file_path, "w") as f:
for info in info_list:
f.write(str(info) + "
")
file_path = "info_list.txt"
# 加载内存中的字典列表
loaded_info_list = load_info_from_file(file_path)
# 更新字典信息
updated_info = update_info(loaded_info_list[0], {"年龄": 26, "姓名": "张三丰", "性别": "男"})
# 替换内存中的字典列表
save_info_to_file(file_path, [updated_info])
```
```python
info = {"年龄": 0, "姓名": "", "性别": ""}
```
第二步:生成三个字典,并把他们追加到列表中。
```python
info_list = []
info1 = {"年龄": 25, "姓名": "张三", "性别": "男"}
info2 = {"年龄": 30, "姓名": "李四", "性别": "女"}
info3 = {"年龄": 22, "姓名": "王五", "性别": "男"}
info_list.append(info1)
info_list.append(info2)
info_list.append(info3)
```
第三步:把列表用open()写入到内存中。
```python
with open("info_list.txt", "w") as f:
for info in info_list:
f.write(str(info) + "
")
```
第四步:设计一个修改模块,能够修改他们的年龄姓名性别等。修改完后替换到内存中。
```python
def update_info(old_info, new_info):
old_info.update(new_info)
return old_info
def load_info_from_file(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
info_list = [eval(line.strip()) for line in lines]
return info_list
def save_info_to_file(file_path, info_list):
with open(file_path, "w") as f:
for info in info_list:
f.write(str(info) + "
")
file_path = "info_list.txt"
# 加载内存中的字典列表
loaded_info_list = load_info_from_file(file_path)
# 更新字典信息
updated_info = update_info(loaded_info_list[0], {"年龄": 26, "姓名": "张三丰", "性别": "男"})
# 替换内存中的字典列表
save_info_to_file(file_path, [updated_info])
```