10_python_文件和异常


日期: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('_______________________________________________')
# ---------------------------------------------------------


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,169评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,894评论 0 17
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,473评论 25 709
  • 今晚的手工课需要准备如下的工具:粘土、剪刀、三根牙签、做粘土的工具刀和棒。 老师示范: 故事主角做出来了,小朋友们...
    智悲德育阅读 2,985评论 0 0
  • 我享受一个人的出游,除了吃饭的时候。 受限于胃口,也可能是开销,一般当地大份的特色菜式落单的人都无缘品尝。即便是下...
    Call_me_竞哥哥阅读 4,455评论 5 12

友情链接更多精彩内容