日期:2017-12-30
作者:秋的懵懂
注意:這里需要自行創(chuàng)建一些用于測試的txt文件饼丘。
# coding = utf-8
# ***********************************************************
# @file python_10_file_traceback.py
# @brief 文件和異常
# @author 魏文應(yīng)
# @date 2017-12-28
# ***********************************************************
# @attention
# 這里需要自行創(chuàng)建文件函匕,文件應(yīng)該在代碼工作區(qū),其中包含:
# 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 關(guān)鍵字會自動關(guān)閉文件
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()函數(shù)去除字符串末尾的空白
filename = 'text_files\pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
# 使用關(guān)鍵字with 時,open()返回的
# 文件對象只在with 代碼塊內(nèi)可用
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' 默認(rèn)就是這個模式
# 寫入模式:'w' 重寫绑青,原來的內(nèi)容會被清除
# 附加模式:'a' 后面添加內(nèi)容,原來的內(nèi)容還在
# 讀寫模式:'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成功執(zhí)行跪腹,則執(zhí)行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關(guān)鍵字(讓python此時什么都不做)
print('\n\n')
print('_______________________________________________')
print("pass關(guān)鍵字(讓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存儲數(shù)據(jù)
print('\n\n')
print('_______________________________________________')
print("json存儲數(shù)據(jù):")
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('_______________________________________________')
# ---------------------------------------------------------