一、内容
二、练习
练习1
题目:文件的增删改查
图示:
代码:
import os
def add(data):
content = data[1] # 文件内容
file_name = data[-1]# 文件名
with open(file_name,'r',encoding='utf-8') as f_read:
lines = f_read.readlines()
with open('b.txt','a',encoding='utf-8') as f_write:
for line in lines:
f_write.write(line)
f_write.write(content)
os.remove(file_name)
os.rename('b.txt',file_name)
with open('b.txt','w',encoding='utf-8') as f:
pass
def delete(data):
content = data[1] # 文件内容
file_name = data[-1] # 文件名
with open(file_name,'r',encoding='utf-8') as f_read:
lines = f_read.readlines()
with open('b.txt','w',encoding='utf-8') as f_write:
for line in lines:
if content in line:
continue
f_write.write(line)
os.remove(file_name)
os.rename('b.txt',file_name)
with open('b.txt','w',encoding='utf-8') as f:
pass
def change(data):
content = data[1]
file_name = data[-1]
with open(file_name,'r',encoding='utf-8') as f_read:
lines = f_read.readlines()
with open('b.txt','w',encoding='utf-8') as f_write:
user_change_content = input('Please enter new content:').strip()
for line in lines:
if content in line:
f_write.write(user_change_content)
f_write.write('\n')
continue
f_write.write(line)
os.remove(file_name)
os.rename('b.txt', file_name)
with open('b.txt','w',encoding='utf-8') as f:
pass
def search(data):
content = data[1] # 文件内容
file_name = data[-1]# 文件名
with open(file_name,'r',encoding='utf-8') as f:
for i,line in enumerate(f,1):
if content in line:
print(i,line)
user_dic = {
'add':add,
'delete':delete,
'change':change,
'search':search
}
while True:
user = input('Please enter the command:').strip()
user_l = user.split() # 将用户输入的命令进行切片,以空格为分隔符,得到一个列表
if len(user_l) != 3: # 当这个列表的参数小于3个提示用户缺少参数
print('Missing parameters or Content not found!')
continue
if not user or not user_l[0] in user_dic: # 当用户输入为空或列表的第一个参数不在字典user_dic里时提示用户无效的输入
print('Invalid input!')
continue
if user_l[0] in user_dic: # 当列表中的第一个元素在user_dic中时
if os.path.exists(user_l[-1]):# 当列表中的最后一个元素(即用户输入的文件名)存在时
user_dic[user_l[0]](user_l) # 调用相对应的函数功能,将列表当作实参进行传递
else:
print('The file you want to operate does not exist,please try again.')
输出结果:
a.txt原文件:
1、增加
例:往a.txt文件后面增加字符串"xxxxxxxxxxxxxxxxxx"
输入:add xxxxxxxxxxxxxxxxxx a.txt
输出结果:
2、删除
例:删除指定字符串的所在的行,如带有"knight"关键字的所在的行
输入:delete knight a.txt
输出结果:
3、更改
例:更改指定字符串所在的行,如将带有"knight"关键字所在的行更改为"xxxxxxxxxxxxxxxxxx"
输入:change knight a.txt,后再输入要更改的内容:xxxxxxxxxxxxxxxxxx
输出结果:
4、查找
例:查找包含有“knight”关键字的行并显示出行号来
输入:search knight a.txt
输出结果:
三、英语
1、file
[faɪl] n.文件
2、Directory
[dəˈrɛktəri; (also) daɪˈrɛktəri] n.目录
3、command
[kə'mænd] n.命令
4、import
['ɪmpɔt] vt.导入