10.1

with open("learning_python.txt")as fob:
print("print_1:")
data=fob.read()
print(data)
print("print_2:")
fob.seek(0,0)
for line in fob:
print(line.strip())
print("print_3:")
fob.seek(0,0)
lines=fob.readlines()
for line in lines:
print(line.strip())
PS:注意文件指针,使用方法tell()和seek()
10.2
with open("learning_python.txt")as fob:
fob.seek(0,0)
lines=fob.readlines()
for message in lines:
print(message.replace("Python","C"))
10.4
#coding=gbk
while True:
name=input("请输入用户名,退出则输入0:")
if(name=="0"):
break
with open("name.txt","a") as fob:
fob.write(name)
print("欢迎登陆!"+name)
10.8
def showfile(filename):
try:
with open(filename) as f:
message=f.read()
except FileNotFoundError:
msg="The file "+filename+" is not exsit!"
print(msg)
else:
print("The file shows:")
print(message)
if __name__ == '__main__':
showfile("cat.txt")
showfile("hehe.txt")
showfile("dog.txt")
