10-1 Python学习笔记
with open('learning_python.txt') as txt:
contents = txt.read()
print(contents.rstrip())
with open('learning_python.txt') as txt:
for line in txt:
print(line.rstrip())
with open('learning_python.txt') as txt:
lines = txt.readlines()
for line in lines:
print(line.rstrip())
输出
In Python you can program.
In Python you can play game.
In Python you can kill people.
In Python you can program.
In Python you can play game.
In Python you can kill people.
In Python you can program.
In Python you can play game.
In Python you can kill people.
10-2 C语言学习笔记
with open('learning_python.txt') as txt:
lines = txt.readlines()
for line in lines:
print(line.replace('Python','C').rstrip())
输出
In C you can program.
In C you can play game.
In C you can kill people.
10-3 访客
filename = "guest.txt"
name = input("Please input your name:")
with open(filename,'w') as file_object:
file_object.write(name)
10-4 访客名单
filename = "guest_book.txt"
name = input("Please input your name:")
while name != 'quit':
print("Hello, "+name)
with open(filename,'a') as file_object:
file_object.write(name)
file_object.write('\n')
name = input("Please input your name:")
10-6 加法运算
a = input("Please input a:")
b = input("Please input b:")
try:
a1=int(a)
b1=int(b)
except ValueError:
print("Please input two number!")
else:
print(str(a1+b1))
10-7 加法计算器
while True:
a = input("Please input a:")
b = input("Please input b:")
if a == 'q':
break
try:
a1=int(a)
b1=int(b)
except ValueError:
print("Please input two number!")
else:
print(str(a1+b1))
10-8 猫和狗
filename1 = "cats.txt"
filename2 = "dogs.txt"
try:
with open(filename1) as object_file:
contents = object_file.read()
print(contents.rstrip())
with open(filename2) as object_file:
contents = object_file.read()
print(contents.rstrip())
except FileNotFoundError:
print("There is no such a file!")