10.1 从文件中读取数据
  10.1.1 读取整个文件

  with open(~) as object:

    contents=object.read()

with open('C:/Users/jou/Desktop/input.txt') as file_object:
contents=file_object.read()
print(contents.rstrip())

  10.1.2 文件路径

  #文件路径读取方式1
  filepath='C:/Users/jou/Desktop/input.txt'
  #文件路径读取方式2
  filepath=r'C:\Users\jou\Desktop\input.txt'
  #文件路径读取方式3
  filepath='C:\\Users\\jou\\Desktop\\input.txt'

  10.1.3 逐行读取

filepath='C:/Users/jou/Desktop/input.txt'
with open
(filepath) as file_object:
for line in file_object:
#因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,
#因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。
#.rstrip() 消除空白行
print(line.rstrip())

  10.1.4 创建一个包含文件各行内容的列表

filepath='C:/Users/jou/Desktop/input.txt'
with
open(filepath) as file_object:
lines = file_object.readlines()
#打印列表
print(lines)
#逐行打印列表元素
for line in lines:
print(line.rstrip())

  10.1.5 使用文件的内容

filepath='C:/Users/jou/Desktop/input.txt'
with open(filepath) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip() #.strip() 消除所有空格
#打印列表各元素组成的字符串
print(pi_string)

  10.1.6 包含一百万位的大型文件

#文件路径读取方式1
filepath=r'D:\h5.csv'
#创建一个包含文件各行内容的列表
with open(filepath) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
print(len(lines))

10.2 写入文件

  10.2.1 写入空文件

#调用open() 时需要提供另一个实参,告诉Python你要写入打开的文件。
#读取模式 ('r' )、写入模式 ('w' )、附加模式 ('a' )或让你能够读取和写入文件的模式('r+' )。
#如果你省略了模式实参,Python将以默认的只读模式打开文件。
#如果你要写入的文件不存在,函数open() 将自动创建它。
filepath='C:\\Users\\jou\\Desktop\\output.txt'
with open(filepath, 'w') as file_object:
file_object.write("I love programming.")

  10.2.2 写入多行

#以写入('w' )模式打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
#函数write() 不会在你写入的文本末尾添加换行符
#要让每个字符串都单独占一行,需要在write() 语句中包含换行符
filepath='C:\\Users\\jou\\Desktop\\output1.txt'
with open(filepath, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
filepath='C:\\Users\\jou\\Desktop\\output2.txt'
with open(filepath, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")

  10.2.3 附加到文件

filename='C:\\Users\\jou\\Desktop\\output.txt'
#如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式 打开文件。
#你以附加模式打开文件时,Python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。
#如果指定的文件不存在,Python将为你创建一个空文件。
with open(filename, 'a') as file_object:
file_object.write("\nI also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")

10.3 异常

  Python使用被称为异常 的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。

  如果你编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

  异常是使用try-except 代码块处理的。try-except 代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。

  使用了try-except 代码块时,即便出现异常,程序也将继续运行:显示你编写的友好的错误消息,而不是令用户迷惑的traceback。

  10.3.1 处理ZeroDivisionError异常

  division.py  

print(5/0)
IndentationError: unexpected indent
print(5/0)
ZeroDivisionError: division by zero
print(5/0)

  10.3.2 使用try-except代码块

try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")

  10.3.3 使用异常避免崩溃

  10.3.4 else代码块 

#通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。
#错误是执行除法运算的代码行导致的,因此我们需要将它放到try-except 代码块中。
#这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
##10.3.4 else 代码块
else:
print(answer)

   10.3.5 处理FileNotFoundError异常

filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read() filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)

    10.3.6 分析文本

filename = r"D:\h5.csv"
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# 计算文件大致包含多少个单词
# 方法split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")

  10.3.7 使用多个文件

#invalid syntax 该问题是语法错误,说明你的语句不合规则
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.") filenames = [r"D:\h5.csv", r"D:\h6.csv", r"D:\h7.csv"]
for filename in filenames:
count_words(filename)

  10.3.8 失败时一声不吭

try:
print(5/0)
except ZeroDivisionError:
pass

10.4 存储数据

  10.4.1 使用json.dump()和json.load()

import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
#使用json.dump() 来存储这组数字
#函数json.dump() 接受两个实参:要存储的数据以及可用于存储数据的文件对象。
#我们指定了要将该数字列表存储到其中的文件的名称。通常使用文件扩展名.json来指出文件存储的数据为JSON格式。
#我们以写入模式打开这个文件,让json 能够将数据写入其中
with open(filename, 'w') as f_obj:
#我们使用函数json.dump() 将数字列表存储到文件numbers.json中
json.dump(numbers, f_obj) #这次我们以读取方式打开这个文件
filename = 'numbers.json'
#使用函数json.load() 加载存储在numbers.json中的信息,并将其存储到变量numbers 中
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)

  10.4.2 保存和读取用户生成的数据

import json
# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")

  10.4.3 重构

  代码能够正确地运行,但可做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构 。

  重构让代码更清晰、更易于理解、更容易扩展。

import json
#代码能够正确地运行,但可做进一步的改进—
#将代码划分为一系列完成具体工作的函数。这样的过程被称为重构
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username def get_new_username():
"""提示用户输入用户名"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()

读书笔记「Python编程:从入门到实践」_10.文件和异常的更多相关文章

  1. 读书笔记「Python编程:从入门到实践」_9.类

    9.1 创建和使用类 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想. OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. 把 ...

  2. 读书笔记「Python编程:从入门到实践」_11.测试函数

    11.1 测试函数 要学习测试,得有要测试的代码.下面是一个简单的函数,它接受名和姓并返回整洁的姓名: def get_formatted_name(first, last): "" ...

  3. 读书笔记「Python编程:从入门到实践」_8.函数

    8.1 定义函数 def greet_user(): # def 来告诉Python你要定义一个函数.这是函数定义 """Hello World""& ...

  4. 读书笔记「Python编程:从入门到实践」_7.用户输入和while循环

    7.1 函数input()的工作原理 函数input() 让程序暂停运行,等待用户输入一些文本.获取用户输入后,Python将其存储在一个变量中,以方便你使用. message = input(&qu ...

  5. 读书笔记「Python编程:从入门到实践」_6.字典

    6.1 一个简单的字典 alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points' ...

  6. 读书笔记「Python编程:从入门到实践」_5.if语句

    5.1 一个简单示例 cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print(car.up ...

  7. 读书笔记「Python编程:从入门到实践」_4.操作列表

    4.1 遍历整个列表   4.1.1 深入地研究循环   4.1.2 在for循环中执行更多的操作   4.1.3 在for循环结束后执行一些操作  例 magicians = ['alice', ' ...

  8. 读书笔记「Python编程:从入门到实践」_3.列表简介

    3.1 列表是什么 列表 由一系列按特定顺序排列的元素组成. 在Python中,用方括号([] )来表示列表,并用逗号来分隔其中的元素. 3.1.1 访问列表元素 指出列表的名称,再指出元素的索引   ...

  9. 读书笔记「Python编程:从入门到实践」_2.变量和简单数据类型

    做了大半年RPA了,用的工具是Kapow. 工作没有那么忙,不想就这么荒废着,想学点什么.就Python吧. 为期三个月,希望能坚持下来. 2.1 变量的命名和使用 变量名只能包含字母.数字和下划线. ...

随机推荐

  1. Huawei-R&S-网络工程师实验笔记20190608-VLAN划分基础(基于端口、MAC地址、子网地址、协议)

    >Huawei-R&S-网络工程师实验笔记20190608-VLAN划分基础(基于端口.MAC地址.子网地址.协议) >>实验开始,先上拓扑图参考: 一.基于端口划分VLAN ...

  2. 微信公众号:1-IDHTTP控件:GET/POST 请求获取access_token

    (图来源于方蓓?) 首先要理解公众号的流程.通过图知道,我们要:1.你要有个web服务器,用于和微信服务器通讯.你的web服务器必须让微信服务器能找到.2.通信要求按照微信公众号开发要求的格式提供相关 ...

  3. 【codeforces 785E】Anton and Permutation

    [题目链接]:http://codeforces.com/problemset/problem/785/E [题意] 给你一个初始序列1..n顺序 然后每次让你交换任意两个位置上面的数字; 让你实时输 ...

  4. UVa - 12661 - Funny Car Racing

    先上题目: 12661 Funny Car RacingThere is a funny car racing in a city with n junctions and m directed ro ...

  5. angular5 httpclient的示例实战

    摘要: 从angular 4.3.0 以后的版本开始使用httpclient,替换了之前的http,引用的包路径已经变为了angular/common/http了 一个基础的 httpclient 样 ...

  6. [Javascript] AbortController to cancel the fetch request

    We are able to cancel the fetch request by using AbortController with RxJS Observable. return Observ ...

  7. 通过telent、php深入了解http协议

    HTTP协议:简单点就是client怎么问.server如何答. 重要性:webservice 还是rest做大型架构都离不开对http协议的认识,甚至能够简化的说webservice =  http ...

  8. Yum重装走过的坑

    今天因为用yum方式安装mongo遇到报错,从而我选择卸载yum并重新安装. 我先选择了用rpm方式进行重装,从163的packages列表里面找到64位redhat6.5可以用的三个rpm包,安装过 ...

  9. 第十七周自由练习项目——acm 学生最高最低成绩

    /* *程序的版权和版本号声明部分: *Copyright(c)2014,烟台大学计算机学院学生 *All rights reserved. *文件名:acm 学生最高与最低成绩 *作者:刘中林 *完 ...

  10. 配置Java连接池的两种方式:tomcat方式以及spring方式

    1. tomcat方式:在context.xml配置连接池,然后在web.xml中写配置代码(也能够在server.xml文件里配置连接池).这两种方法的差别是:在tomcat6版本号及以上中cont ...