10-1 Python学习笔记
learning_python.txt
In Python you can be angry
In Python you can be excited
In Python you can say nothing
main.py
with open('learning_python.txt') as file:
print("打印整个文件")
contents = file.read()
print(contents.rstrip())
with open('learning_python.txt') as file:
print("遍历文件对象")
for line in file:
print(line.rstrip())
with open('learning_python.txt') as file:
print("with外打印列表")
lines = file.readlines()
for line in lines:
print(line.rstrip())
输出结果是:
打印整个文件
In Python you can be angry
In Python you can be excited
In Python you can say nothing
遍历文件对象
In Python you can be angry
In Python you can be excited
In Python you can say nothing
with外打印列表
In Python you can be angry
In Python you can be excited
In Python you can say nothing
10-2 C语言学习笔记
with open('learning_python.txt') as file:
print("with外打印列表")
lines = file.readlines()
for line in lines:
print(line.replace("Python","C").rstrip())
输出结果是:
with外打印列表
In C you can be angry
In C you can be excited
In C you can say nothing
10-3 访客
filename = 'guest.txt'
with open(filename,'w') as file:
name = input("请输入你的名字:")
file.write(name)
测试样例:mizuha
guest.txt
mizuha
10-4 访客名单
filename = 'guest_book.txt'
with open(filename,'w') as file:
while True:
name = input("请输入你的名字:")
if name == 'stop':
break
print("欢迎"+name)
file.write(name+'\n')
测试样例:
请输入你的名字:mizuha
欢迎mizuha
请输入你的名字:hinata
欢迎hinata
请输入你的名字:stop
guest_book.txt
mizuha
hinata
10-8 猫和狗
dogsname = 'dogs.txt'
catsname = 'cats.txt'
try:
with open(catsname) as file:
contents = file.read()
print(contents.rstrip())
with open(dogsname) as file:
contents = file.read()
print(contents.rstrip())
except FileNotFoundError:
print("找不到文件")
dogs.txt存在时,输出结果是:
blackcat
bluecat
redcat
mica
gabrielle
rafael
文件移走后,输出结果是:
blackcat
bluecat
redcat
找不到文件
10-9 沉默的猫和狗
dogsname = 'dogs.txt'
catsname = 'cats.txt'
try:
with open(catsname) as file:
contents = file.read()
print(contents.rstrip())
with open(dogsname) as file:
contents = file.read()
print(contents.rstrip())
except FileNotFoundError:
pass
输出结果是:
blackcat
bluecat
redcat
10-11 喜欢的数字
import json
filename = 'number.json'
with open(filename,'w') as fobj:
number = input("Please input your favourite number: ")
json.dump(number,fobj)
with open(filename) as fobj:
number = json.load(fobj)
print("I know your favourite number! It's "+str(number))
输出结果是:
Please input your favourite number: 23
I know your favourite number! It's 23
10-12 记住喜欢的数字
import json
filename = 'number.json'
for i in range(2):
try:
with open(filename) as fobj:
number = json.load(fobj)
print("I know your favourite number! It's " + str(number))
except FileNotFoundError:
with open(filename, 'w') as fobj:
number = input("Please input your favourite number: ")
json.dump(number, fobj)
输出结果是:
Please input your favourite number: 23
I know your favourite number! It's 23
文件number.json:
"23"