日期:2017-12-30
作者:秋的懵懂
注意:这里需要自行创建一些用于测试的txt文件。
# coding = utf-8
# ***********************************************************
# @file python_10_file_traceback.py
# @brief 文件和异常
# @author 魏文应
# @date 2017-12-28
# ***********************************************************
# @attention
# 这里需要自行创建文件,文件应该在代码工作区,其中包含:
# text_files\pi_digits.txt
# text_files\programing.txt
# text_files\All_But_Lost.txt
# numbers.json
# ***********************************************************
# ---------------------------------------------------------
# 打开一个txt文件并显示
print('\n\n')
print('_______________________________________________')
print("打开一个txt文件并显示:")
# with 关键字会自动关闭文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
with open("text_files\pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
filename = "text_files\pi_digits.txt"
with open(filename) as file_object:
for line in file_object:
print(line)
# rstrip()函数去除字符串末尾的空白
filename = 'text_files\pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
# 使用关键字with 时,open()返回的
# 文件对象只在with 代码块内可用
filename = 'text_files\pi_digits.txt'
with open(filename) as file_object:
# readlines()整行读取,存于列表
lines = file_object.readlines()
# with外部使用
for line in lines:
print(line.rstrip())
#
filename = 'text_files\pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
# 定义一个字符变量
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input('Enter your birthday, in the from mmddyy:')
if birthday in pi_string:
print('Your birthday appears in the pi.' )
else:
print('Does not appears.')
print('_______________________________________________')
# ---------------------------------------------------------
# ---------------------------------------------------------
# 写入文件
print('\n\n')
print('_______________________________________________')
print("写入文件:")
# 读取模式:'r' 默认就是这个模式
# 写入模式:'w' 重写,原来的内容会被清除
# 附加模式:'a' 后面添加内容,原来的内容还在
# 读写模式:'r+'
filename = 'text_files\programing.txt'
with open(filename, 'w') as file_object:
file_object.write('I love programing!\n')
file_object.write('I love creating new games!\n')
with open(filename, 'a') as file_object:
file_object.write('I also love finding meaning' +
' in large datasets.\n')
file_object.write('I love creating apps that can' +
'run in a browser.\n')
with open(filename, 'r') as file_object:
for line in file_object.readlines():
print(line.rstrip())
print('_______________________________________________')
# ---------------------------------------------------------
# ---------------------------------------------------------
# 异常处理
print('\n\n')
print('_______________________________________________')
print("异常处理:")
# 处理除零异常
try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
# 简单计算器
print('Give me two number, and I will divide them.')
print("Enter 'q' to quit.")
while True:
first_number = input('\nInput first number:')
if first_number == 'q':
break
second_number = input('\nInput second number:')
if second_number == 'q':
break
# try-except-else try成功执行,则执行else
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print('You can divide by 0!')
else:
print(answer)
# 文件不存在异常处理
file_name = 'alice.txt'
try:
with open(file_name) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
message = "\nSorry, the file " + file_name + \
" dose not exist"
print(message)
# 分析文本
file_name = 'text_files\All_But_Lost.txt'
try:
with open(file_name) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
message = "\nSorry, the file " + file_name + \
" dose not exist"
print(message)
else:
# split()生成列表,元素为所有文本单词
words = contents.split()
num_words = len(words)
print('\nThe file ' + file_name + ' has about ' +
str(num_words) + ' words.')
print('_______________________________________________')
# ---------------------------------------------------------
# ---------------------------------------------------------
# pass关键字(让python此时什么都不做)
print('\n\n')
print('_______________________________________________')
print("pass关键字(让python此时什么都不做):")
def count_words(file_name):
try:
with open(file_name) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# python 什么也没有做
pass
else:
# split()生成列表,元素为所有文本单词
words = contents.split()
num_words = len(words)
print('\nThe file ' + file_name + ' has about ' +
str(num_words) + ' words.')
file_names = ['text_files\All_But_Lost.txt',
'text_files\pi_digits.txt',
'text_files\programing.txt',
'none.txt',]
for file_name in file_names:
count_words(file_name)
print('_______________________________________________')
# ---------------------------------------------------------
# ---------------------------------------------------------
# json存储数据
print('\n\n')
print('_______________________________________________')
print("json存储数据:")
import json
numbers = [1, 3, 2, 4, 6, 9]
file_name = 'numbers.json'
with open(file_name, 'w') as f_obj:
# 写入
json.dump(numbers, f_obj)
with open(file_name) as f_obj:
# 读取
read_numbers = json.load(f_obj)
print(read_numbers)
# 写入
user_name = input('What is your name?')
with open(file_name, 'w') as file_object:
json.dump(user_name, file_object)
print('We will remenber you when you come back, '
+ user_name + '!')
# 读取
with open(file_name) as file_object:
user_name = json.load(file_object)
print('Welcome back ' + user_name + '!')
print('_______________________________________________')
# ---------------------------------------------------------