用python第一步,生成一个字典,关键字包含年龄,姓名,性别。 第二步,生成三个字典,并把他们追加到列表中 第三步,把列表用open()写入到内存中; 第四步,设计一个修改模块,能够修改他们的年龄姓
第一步:生成一个字典,关键字包含年龄,姓名,性别。
```python
info = {"年龄": 25, "姓名": "张三", "性别": "男"}
```
第二步:生成三个字典,并把他们追加到列表中。
```python
info_list = []
info1 = {"年龄": 30, "姓名": "李四", "性别": "女"}
info2 = {"年龄": 28, "姓名": "王五", "性别": "男"}
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 modify_info(old_info, key, value):
old_info[key] = value
return old_info
def append_to_file(file_name, info):
with open(file_name, "a") as f:
f.write(str(info) + "
")
for info in info_list:
print("修改前:", info)
modified_info = modify_info(info, "年龄", 26)
modified_info = modify_info(modified_info, "姓名", "钱七")
modified_info = modify_info(modified_info, "性别", "女")
print("修改后:", modified_info)
append_to_file("info_list.txt", modified_info)
```
```python
info = {"年龄": 25, "姓名": "张三", "性别": "男"}
```
第二步:生成三个字典,并把他们追加到列表中。
```python
info_list = []
info1 = {"年龄": 30, "姓名": "李四", "性别": "女"}
info2 = {"年龄": 28, "姓名": "王五", "性别": "男"}
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 modify_info(old_info, key, value):
old_info[key] = value
return old_info
def append_to_file(file_name, info):
with open(file_name, "a") as f:
f.write(str(info) + "
")
for info in info_list:
print("修改前:", info)
modified_info = modify_info(info, "年龄", 26)
modified_info = modify_info(modified_info, "姓名", "钱七")
modified_info = modify_info(modified_info, "性别", "女")
print("修改后:", modified_info)
append_to_file("info_list.txt", modified_info)
```