您的位置:首页 > 编程语言 > Python开发

Python学习笔记(7)文件和异常

2019-05-07 14:43 387 查看
[code]#encoding=gbk

import json

#1.读取文件
#函数open() 返回一个表示文件的对象。再用方法read()读取这个文件的全部内容,并作为字符串存储在变量contents中。
with open('file.txt') as file_object:
contents = file_object.read()
print(contents)

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

#创建一个包含文件各行内容的列表
filename = 'file.txt'
with open(filename) as file_object:
lines = file_object.readlines()   #用方法readlines()从文件中读取每一行,并将其存储在一个列表中
print(lines)
for line in lines:
print(line.rstrip())

#2.写入文件
#写入空文件
filename = 'filewrite.txt'
with open(filename,'w') as file_object:   #读取模式(‘r’)、写入模式(‘w’)、附加模式(‘a’)、读取和写入模式(‘r+’),不传参则是只读模式;
file_object.write('I like learning!') #注意:Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。

#写入多行
#函数write()不会在你写入的文本末尾添加换行符,因此如果写入多行时没有指定换行符,文件看起来可能不是希望的那样。
filename = 'filewrite2.txt'
with open(filename,'w') as file_object:
file_object.write('I like learning!\n')
file_object.write('I like working!')

#3.向文件追加值
filename = 'file.txt'
with open(filename,'a') as file_object:
file_object.write('大数据产品部\n')

#4.异常
#Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。
#如果程序里编写了处理该异常的代码,程序将被继续运行;如果程序里未对异常进行处理,程序将停止,并显示一个traceback,其中包
#含有关异常的报告。异常是使用try-except代码块处理的。try-except代码块让Python执行指定的操作,同时告诉Python发生异常
#是怎么办。使用了try-except代码块时,即便出现异常,程序也将继续运行:显示编写的友好的错误消息。

#使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("Error:You cann't divide by zero!")

filename = 'test.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("Error:The file '" + filename + "' does not exist.")

filename = 'file.txt'
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("Error:The file '" + filename + "' does not exist.")
else:
words = contents.split()  #调用split()方法,生成一个列表包含这个文件中的所有单词;
num_words = len(words)
print(num_words)

#存储数据
#用户关闭程序时,总是要保存他们提供的一些信息,一种简单的方式是使用模块json来存储数据。
#模块json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据

#json.dump()存储数字列表
numbers = [1,3,5,6,8,9]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)    #使用函数json.dump()将数字列表存储到文件中;

#用json.load()将这个列表读取到内存中
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: