笨方法学Python,习题16 – 21
版本:3.8.0
编辑器:Visual Studio Code
习题16到21讲的是文件的读写和函数的基础,可以通过一个实例来同时练习他们。在下列情景中,我将设计几个函数用于实现文件的读、写和复制。
其实关于file的操作原本想用对象处理的,后来发现每个方法的open方式都不一样,最后还是改成用指定文件名的方式了
文件内容读取函数
def printFileContent(fileName):
file = open(fileName);
line = file.readline();
print("\n<< 开始读取 >>\n");
while line:
print("%s" %line, end = "");
line = file.readline();
print("\n<< 读取完成 >>\n");
file.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
文件写入函数
def rewriteFlieContent(fileName, contentList):
file = open(fileName, 'w');
file.truncate();
iterator = iter(contentList);
for text in iterator:
file.write(text + "\n");
file.close(); # 关闭文件,保存修改
print("<< 写入完成 >>");
file.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
续写文本内容函数
def insertContent(fileName):
file = open(fileName, 'a');
text = input("请输入一行新内容:");
file.write(text + "\n");
print("<< 写入完成 >>");
file.close();
- 1
- 2
- 3
- 4
- 5
- 6
在主函数中进行测试
import myFunction as func;
import sys;
"""
打印菜单内容,并接收用户输入的序号
@return 返回一个字符串,表示用户输入的序号
"""
def getCmd(fileName):
print("当前打开的文件:" + fileName);
print("[1]覆写文件\t\t[2]读取文件内容\t\t[3]写入一行新内容");
return input("请输入序号 >>> ");
fileName = "readme.txt"; # 直接写死文件名,不再重复从cmd中读取
try:
# 转成int型,通过异常捕捉确认输入的是否是数字
cmd = int(getCmd(fileName));
except ValueError:
print("错误:请输入数字");
sys.exit(); # 中断程序,最常用的中断方式。
if cmd == 1:
# 覆写文件
print("覆写文件");
content = list();
token = True;
while token:
text = input("请输入一行新内容(输入False以结束读取) >>> ");
if text == "False":
# 二次确认是否结束,让False也可以被写入文件中
if input("确认结束输入? Y/N >>> ") == "Y":
token = False;
else:
content.append(text);
else:
content.append(text);
func.rewriteFlieContent(fileName, content);
print("<< 覆写完成 >>");
elif cmd == 2:
# 读取文件内容
print("读取文件内容");
func.printFileContent(fileName);
elif cmd == 3:
# 写入新内容
print("写入新内容");
func.insertContent(fileName);
else:
# 指令错误
print("指令错误");
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
这边就是参考以前C++控制台程序的做法了,接收用户指令判定要执行的功能,并调用相关函数。这样既可以练习文本的读写,同时也练习了函数的定义与使用方式,一举两得。