输入文件:learning_python.txt如下:
in python you can write
in python you can see
in python you can code
in python you can't find yourself a girlfriend
代码如下:
#10-1
filename = 'learning_python.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("\n")
with open(filename) as file_object:
contents = file_object.read()
print(contents.rstrip())
print("\n")
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
print("\n")
#10-2
for line in lines:
print(line.replace('python', 'C').rstrip())
print("\n")
#10-3
filename = 'guest.txt'
with open(filename, 'w') as file_object:
while True:
print("What's your name? Enter q to quit")
name = input()
if name == 'q':
break
file_object.write(name + '\n')
#10-6
while True:
num1 = input("Please input 1st numbers: ")
num2 = input("Please input 2nd numbers: ")
try:
print(int(num1) + int(num2))
except ValueError:
print("No, you didn't enter integer, Please Enter again")
else:
break
输入如下:
good
man
q
e
r
9
8
输出如下:
in python you can write
in python you can see
in python you can code
in python you can't find yourself a girlfriend
in python you can write
in python you can see
in python you can code
in python you can't find yourself a girlfriend
in python you can write
in python you can see
in python you can code
in python you can't find yourself a girlfriend
in C you can write
in C you can see
in C you can code
in C you can't find yourself a girlfriend
What's your name? Enter q to quit
What's your name? Enter q to quit
What's your name? Enter q to quit
Please input 1st numbers: Please input 2nd numbers: No, you didn't enter integer, Please Enter again
Please input 1st numbers: Please input 2nd numbers: 17