Python -- 9. 文件和异常

来源:互联网 发布:excel更改坐标轴数据 编辑:程序博客网 时间:2024/06/06 10:59

1. 从文件中读取数据
(1).读取整个文件

with open('pi_digits.txt') as file_object:    contents = file_object.read()    print(contents)
  • open(‘pi_digits.txt’) 返回一个表示文件pi_digits.txt 的对象
  • 在这个程序中,注意到我们调用了open() ,但没有调用close() ;关键字with 在不再需要访问文件后将其关闭。
  • 你也可以调用open() 和close() 来打开和关闭文件,但这样做时,如果程序存在bug,导致close()语句未执行,文件将不会关闭。

输出的实际内容相比于原始文件,该输出唯一不同的地方是末尾多了一个空行。
为何会多出这个空行呢?
因为read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。
要删除多出来的空行,可在print 语句中使用rstrip() :

with open('pi_digits.txt') as file_object:    contents = file_object.read()    print(contents.rstrip())

(2).文件路径
当你将类似pi_digits.txt这样的简单文件名传递给函数open() 时,Python将在当前执行的文件(即.py程序文件)所在的目录中查找文件。
相对文件路:

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

在Windows系统中,在文件路径中使用反斜杠(\ )而不是斜杠(/ ):

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

绝对文件路径:

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

(3).逐行读取

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

我们打印每一行时,发现空白行更多了.
为何会出现这些空白行呢?
因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符。
因此每行末尾都有两个换行符:一个来自文件,另一个来自print 语句。
要消除这些多余的空白行,可在print 语句中使用rstrip()

print(line.rstrip())

(4).创建一个包含文件各行内容的列表

  • 使用关键字with 时,open() 返回的文件对象只在with 代码块内可用。
  • 如果要在with 代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with 代码块外使用该列表。
filename = 'pi_digits.txt'with open(filename) as file_object:    lines = file_object.readlines()for line in lines:    print(line.rstrip())

方法readlines() 从文件中读取每一行,并将其存储在一个列表中;
接下来,该列表被存储到变量lines 中;
在with 代码块外,我们依然可以使用这个变量。

(5).包含一百万位的大型文件
只打印到小数点后50位

print(pi_string[:52] + "...")

(6).文件中包含字符串

birthday = input("Enter your birthday, in the form mmddyy: ")if birthday in pi_string:    print("Your birthday appears in the first million digits of pi!")else:    print("Your birthday does not appear in the first million digits of pi.")


2. 写入文件
(1).写入空文件

filename = 'programming.txt'with open(filename, 'w') as file_object:    file_object.write("I love programming.")
  • 在这个示例中,调用open() 时提供了两个实参。第一个实参也是要打开的文件的名称;第二个实参(’w’)告诉Python,我们要以写入模式 打开这个文件。
  • 打开文件时,可指定读取模式 (’r’ )、写入模式 (’w’ )、附加模式 (’a’)或让你能够读取和写入文件的模式(’r+’ )。
  • 如果你省略了模式实参,Python将以默认的只读模式打开文件。
  • 以写入(’w’)模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件。
  • 注意:Python只能将字符串写入文本文件。
  • 要将数值数据存储到文本文件中,必须先使用函数str() 将其转换为字符串格式。

(2).写入多行

  • 函数write() 不会在你写入的文本末尾添加换行符。
  • 要让每个字符串都单独占一行,需要在write() 语句中包含换行符。
filename = 'programming.txt'with open(filename, 'w') as file_object:    file_object.write("I love programming.\n")    file_object.write("I love creating new games.\n")

(3).附加到文件

  • 如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式 打开文件。
  • python不会在返回文件对象前清空文件,而你写入到文件的行都将添加到文件末尾。
  • 如果指定的文件不存在,Python将为你创建一个空文件。
filename = 'programming.txt'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")


3. 异常

  • Python使用被称为异常 的特殊对象来管理程序执行期间发生的错误。
  • 每当发生让Python不知所措的错误时,它都会创建一个异常对象。
  • 如果你编写了处理该异常的代码,程序将继续运行;
  • 如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。

(1). 处理ZeroDivisionError 异常
使用try-except 代码块

  • try-except 代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。
  • 使用了try-except 代码块时,即便出现异常,程序也将继续运行:
try:    answer = int(first_number) / int(second_number)except ZeroDivisionError:    print("You can't divide by 0!")else:    print(answer)

(2). 处理FileNotFoundError 异常

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)

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

>>> title = "Alice in Wonderland">>> title.split()['Alice', 'in', 'Wonderland']

(4). 失败时一声不吭
except 代码块中明确地告诉Python什么都不要做,Python有一个pass 语句,可在代码块中使用它来让Python什么都不要做.

def count_words(filename):    """计算一个文件大致包含多少个单词"""    try:        --snip--    except FileNotFoundError:        pass    else:        --snip--filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']for filename in filenames:    count_words(filename)


4. 存储数据

  • 模块json 让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
  • 你还可以使用json在Python程序之间分享数据。
  • 更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。

(1). 使用json.dump() 和json.load()
下面演示了如何使用json.dump() 来存储数字列表:
使用函数json.dump() 将数字列表存储到文件numbers.json

import jsonnumbers = [2, 3, 5, 7, 11, 13]filename = 'numbers.json'with open(filename, 'w') as f_obj:    json.dump(numbers, f_obj)

使用json.load() 将这个列表读取到内存中:

import jsonfilename = 'numbers.json'with open(filename) as f_obj:    numbers = json.load(f_obj)print(numbers)

(2). 保存和读取用户生成的数据

import jsonusername = input("What is your name? ")filename = 'username.json'with open(filename, 'w') as f_obj:    json.dump(username, f_obj)    print("We'll remember you when you come back, " + username + "!")

现在再编写一个程序,向其名字被存储的用户发出问候:

import jsonfilename = 'username.json'with open(filename) as f_obj:    username = json.load(f_obj)    print("Welcome back, " + username + "!")
0 0