笨方法学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
();
文件写入函数
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
();
续写文本内容函数
def insertContent(fileName
):
file = open(fileName
, 'a');
text
= input("请输入一行新内容:");
file.write
(text
+ "\n");
print("<< 写入完成 >>");
file.close
();
在主函数中进行测试
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";
try:
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":
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("指令错误");
这边就是参考以前C++控制台程序的做法了,接收用户指令判定要执行的功能,并调用相关函数。这样既可以练习文本的读写,同时也练习了函数的定义与使用方式,一举两得。