10-1
文件内容:
In Python you can
output a string
define a class
do with file
代码:
with open('py.txt') as file:
contents = file.read()
print(contents)
for content in contents:
print(content)
with open('py.txt') as file:
lines = file.readlines()
print(lines)
输出结果:
In Python you can
output a string
define a class
do with file
In Python you can
output a string
define a class
do with file
['In Python you can\n', 'output a string\n', 'define a class\n', 'do with file']
10-4
代码:
name = ""
with open('guest_book','w') as file:
while True:
name = input("What is you name?(q to quit):")
if name == "q":
break
print("Hello," + name)
file.write("Hello," + name +"\n")
输入:
What is you name?(q to quit):Eric
Hello,Eric
What is you name?(q to quit):Kangkang
Hello,Kangkang
What is you name?(q to quit):Mary
Hello,Mary
What is you name?(q to quit):q
guest_book.txt:
Hello,Eric
Hello,Kangkang
Hello,Mary
10-6
代码:
first = ""
second = ""
while True:
flag = True
first = input("The first number is:")
try:
first_number = int(first)
except ValueError:
print("The input should be a number!")
flag = False
else:
first_number = int(first)
second = input("The second number is:")
try:
second_number = int(second)
except ValueError:
print("The input should be a number!")
flag = False
else:
second_number = int(second)
if flag:
print(first_number + second_number)
quit = input("Do you want to add again(y or n)?")
if quit == "n":
break
输出结果:
The first number is:2
The second number is:3
5
Do you want to add again(y or n)?y
The first number is:2
The second number is:a
The input should be a number!
Do you want to add again(y or n)?y
The first number is:a
The input should be a number!
The second number is:2
Do you want to add again(y or n)?n
10-12
代码:
import json
filename = 'number.json'
number = ""
try:
with open(filename) as f_obj:
number = json.load(f_obj)
except FileNotFoundError:
number = input("What is you favorite number:")
with open(filename,'w') as file:
json.dump(number,file)
print("I have remmember your favorite number!")
else:
print("I know your favorite number!It's " + number +".")
第一次输出结果:
What is you favorite number:5
I have remmember your favorite number!
第二次输出结果:
I know your favorite number!It's 5.