本文是《Python实战从入门到精通》系列之第7篇
【Python】Python实战从入门到精通之一 -- 教你深入理解Python中的变量和数据类型
【Python】Python实战从入门到精通之二 -- 教你使用Python中列表操作
【Python】Python实战从入门到精通之三 -- 教你使用Python中条件语句
【Python】Python实战从入门到精通之四 -- 教你使用Python中字典
【Python】Python实战从入门到精通之五 -- 教你使用文件写入
【Python】Python实战从入门到精通之六 -- 教你读取文件
访客
#!/usr/bin/env python
# -*- coding:utf-8 -*-
user = input('Please input your name:')
with open('guest.txt', 'w') as file_object:
file_object.write(user)
运行j结果:
![](https://i-blog.csdnimg.cn/blog_migrate/1ef83edef4748a5866754cf9b19ebfac.png)
访客名单
#!/usr/bin/env python
# -*- coding:utf-8 -*-
while True:
user = input('Enter quit to end the program\n'+'Please input your name:')
if user == 'q':
break
else:
with open('guest_book.txt', 'r+') as file_object:
contents = file_object.readlines()
pi_string = ''
for line in contents:
pi_string += line.rstrip()
if user in pi_string:
print('\nThis name has existed!\n')
else:
print('\nhello,' + user + '!\n')
file_object.write(user + '\n')
运行结果(红色方框为输入):
文件存储结果:
加法运算
#!/usr/bin/env python
# -*- coding:utf-8 -*-
number1 = input('Please enter the first number:')
number2 = input('Please enter the second number:')
try:
Sum = int(number1) + int(number2)
print('两数字和为:' + str(Sum))
except ValueError:
print('Your enter is not digit.')
输入错误运算结果:
正确运行为:
加法计算器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
while True:
number1 = input('Please enter the first number:')
number2 = input('Please enter the second number:')
try:
Sum = int(number1) + int(number2)
print('\n两数字和为:' + str(Sum))
break
except ValueError:
print('\nYour enter is not digit. Please enter again.\n')
运行结果:
猫和狗
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def print_animals(filename):
"""读取文件内容并打印"""
try:
with open(filename) as file_object:
contents = file_object.read()
print(contents)
except FileNotFoundError:
print('This file is not founded')
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
print('the file of ' + filename + "'s contents are:")
print_animals(filename)
正确运行结果:
文件找不到运行结果:
沉默的猫和狗
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def print_animals(filename):
"""读取文件内容并打印"""
try:
with open(filename) as file_object:
contents = file_object.read()
print('the file of ' + filename + "'s contents are:")
print(contents)
except FileNotFoundError:
pass
filenames = ['cats.txt', 'dogs.txt']
for filename in filenames:
print_animals(filename)
运行结果(cats文件并有找到,但是并未显示结果):