第10章 文件和异常

第10章 文件和异常

1.从文件中读取数据

打开并读取txt文件全部内容
filename = 'pi_digits.txt'
with open(filename) as file_object:#关键字with在不再需要访问文件后将其关闭,python会在合适的时候将其关闭
    #open()接受一个参数:要打开文件的名称
    contents = file_object.read()#read()达到文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行
print(contents.rstrip())#rstrip()删除空行
文件路径

使用相对路径

with open('text_files/filename.txt') as file_object:

让python到文件夹python_work下的文件夹text_files中去查找指定的.txt文件

tip:显示文件路径时,windows系统使用反斜杠(\)而不是斜杠(/),但在代码中依然可以使用斜杠,如果在文件路径中直接使用反斜杠,将引发错误,因为反斜杠用于对字符串中的字符进行转义。

使用绝对文件路径

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:

通过使用绝对路径,可读取系统中任何地方的文件。

逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
		print(line)

此时输出每行末尾都有两个换行符:文件中每行末尾都有一个看不见的换行符,而函数调用print()也会加上一个换行符。

filename = 'pi_digits.txt'
with open(filename) as file_object:
	for line in file_object:
		print(line.rstrip())
创建一个包含文件各行内容的列表
with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())#rstrip()删除空行
使用文件的内容

将文件读取到内存中后,就能以任何方式使用这些数据

字符串处理

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

**注意:**该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

str.strip([chars]);

chars – 移除字符串头尾指定的字符序列。

rstrip() 删除 string 字符串末尾的指定字符(默认为空格.

str.rstrip([chars])

chars – 指定删除的字符(默认为空格)

lstrip() 方法用于截掉字符串左边的空格或指定字符。

str.lstrip([chars])

chars --指定截取的字符

filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
pi_string = ''
for line in lines:
    pi_string += line.strip()

tips:读取文本文件时,python将其中的所有文本都解读为字符串。如果读取的是数,并要将作为数值使用,就必须使用函数int()将转换为整数或使用函数float()将其转换为浮点数

包含一百万位的大型文件
filename = 'pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()
    
print(f"{pi_string[:52]}...")#利用切片
print(len(pi_string))

2.写入文件

打开文件时,可以指定

  • 读取模式 ‘r’

  • 写入模式’w’

  • 附加模式’a’

  • 读写模式’r+’

默认以只读模式打开

filename = 'pp.txt'

with open(filename,'w') as file_object:
    file_object.write("i love programming")

如果写入的文件不存在,函数open()将自动创建它。

以写入模式’w’打开文件时,若指定的文件已经存在,python在返回文件对象前清空该文件的内容。

python只能将字符串写入文本文件,要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式

写入多行

多次调用write就行

附加到文件

如果要给文件添加内容而不是覆盖原有的内容,可以以附加模式’a’打开文件

此时,python不会在返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾。如果指定的文件不存在,python会创建一个新文件

filename = 'pp.txt'

with open(filename,'w') as file_object:
    file_object.write("i love programming\n")
with open(filename,'a') as file_object:
    file_object.write("i don't love programming")

3.异常

python使用称为异常的特殊对象来管理程序执行期间发生的错误。

异常是使用try-except代码块处理的。

处理ZeroDivisionError异常

除数为零错误

使用try-except代码块
try:
    print(5/0)
except ZeroDivisionError:
    print("you can't divide by zero")
使用异常避免崩溃&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: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

try-except-else 有仅在代码块成功执行时才需要运行的代码,这些代码应放在else代码块中。

处理FileNotFoundError异常

找不到文件,查找的文件可能在其他地方,文件名可能不正确,或者这个文件根本不存在。

打开文件的另一种方式

with open(filename,encoding='utf-8') as f:
	contents = f.read()

参数encoding指定了值,在系统的默认编码与要读取文件使用的编码不一致时,必须这样做。

分析文件

方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。

filename = 'alice.txt'
try:
	with open(filename,encoding='utf-8') as f:
		contents = f.read()
except FileNotFoundError:
	print(f"sorry,the file {filename} does not exist.")
else:
	words = contents.split()
	num_words = len(words)
	print(f"the file {filename} has about {num_words} words")
	
静默失败

pass语句充当占位符,python什么都不做

在except代码块中明确地告诉python什么都不要做

放一个pass

4.存储数据

程序把用户提供的信息存储在列表和字典等数据结构中

使用模块json来存储数据

模块json让你能够以将简单的python数据转储到文件中,并在程序再次运行时加载该文件中的数据。可以使用json在python程序之间分享数据。json数据格式并非python专用。

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

1、json.dumps()和json.loads()是json格式处理函数(可以这么理解,json是字符串)
  (1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
  (2)json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)

2、json.dump()和json.load()主要用来读写json文件函数

函数json.dump()接受两个实参:要存储的数据,以及可用于存储数据的文件对象

import json#导入模块json

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f:
    json.dump(numbers, f)#将数字列表存储到文件,number.json中
import json

filename = 'numbers.json'
with open(filename) as f:
    numbers = json.load(f)
    
print(numbers)

保存和读取用户生成的数据
import json
filename = 'username2.json'
try:
    with open(filename) as f:
        username = json.load(f)
except FileNotFoundError:
    username = input("what is your name")
    with open(filename,'w') as f:
        json.dump(username,f)
        print(f"we'll remember you when you come back,{username}")
else:
    print(f"welcome back {username}")

重构

使用函数模块化

import json

def get_stored_username():
    """Get stored username if available."""
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username

def greet_user():
    """Greet the user by name."""
    username = get_stored_username()
    if username:
        print(f"Welcome back, {username}!")
    else:
        username = get_new_username()
        print(f"We'll remember you when you come back, {username}!")

greet_user()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的刺猬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值