大家好,
文件是无处不在的,无论我们使用哪种编程语言,处理文件对于每个程序员都是必不可少的
文件处理是一种用于创建文件、写入数据和从中读取数据的过程,Python 拥有丰富的用于处理不同文件类型的包,从而使得我们可以更加轻松方便的完成文件处理的工作
本文大纲:
-
使用上下文管理器打开文件
-
Python 中的文件读取模式
-
读取 text 文件
-
读取 CSV 文件
-
读取 JSON 文件
Let’s go!
打开文件
在访问文件的内容之前,我们需要打开文件。Python 提供了一个内置函数可以帮助我们以不同的模式打开文件。open()
函数接受两个基本参数:文件名和模式
默认模式是“r”,它以只读方式打开文件。这些模式定义了我们如何访问文件以及我们如何操作其内容。open()
函数提供了几种不同的模式,我们将在后面逐一讨论
下面我们通过 ’Python 之禅‘ 文件来进行后面的讨论学习
- f = open('zen_of_python.txt', 'r')
- print(f.read())
- f.close()
Output:
- The Zen of Python, by Tim Peters
-
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- ...
在上面的代码中,open()
函数以只读模式打开文本文件,这允许我们从文件中获取信息而不能更改它。在第一行,open()
函数的输出被赋值给一个代表文本文件的对象 f
,在第二行中,我们使用 read()
方法读取整个文件并打印其内容,close()
方法在最后一行关闭文件。需要注意,我们必须始终在处理完打开的文件后关闭它们以释放我们的计算机资源并避免引发异常
在 Python 中,我们可以使用 with
上下文管理器来确保程序在文件关闭后释放使用的资源,即使发生异常也是如此
- with open('zen_of_python.txt') as f:
- print(f.read())
Output:
- The Zen of Python, by Tim Peters
-
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- ...
上面的代码使用 with
语句创建了一个上下文,并绑定到变量 f
,所有文件对象方法都可以通过该变量访问文件对象。read()
方法在第二行读取整个文件,然后使用 print()
函数输出文件内容
当程序到达 with 语句块上下文的末尾时,它会关闭文件以释放资源并确保其他程序可以正常调用它们。通常当我们处理不再需要使用的,需要立即关闭的对象(例如文件、数据库和网络连接)时,强烈推荐使用 with 语句
这里需要注意的是,即使在退出 with 上下文管理器块之后,我们也可以访问 f
变量,但是该文件是已关闭状态。让我们尝试一些文件对象属性,看看变量是否仍然存在并且可以访问:
- print("Filename is '{}'.".format(f.name))
- if f.closed:
- print("File is closed.")
- else:
- print("File isn't closed.")
Output:
- Filename is 'zen_of_python.txt'.
- File is closed.
但是此时是不可能从文件中读取内容或写入文件的,关闭文件时,任何访问其内容的尝试都会导致以下错误:
f.read()
Output:
- ---------------------------------------------------------------------------
-
- ValueError Traceback (most recent call last)
-
- ~\AppData\Local\Temp/ipykernel_9828/3059900045.py in <module>
- ----> 1 f.read()
-
- ValueError: I/O operation on closed file.
Python 中的文件读取模式
正如我们在前面提到的,我们需要在打开文件时指定模式。下表是 Python 中的不同的文件模式:
模式说明
-
‘r’ 打开一个只读文件
-
‘w’ 打开一个文件进行写入。如果文件存在,会覆盖它,否则会创建一个新文件
-
‘a’ 打开一个仅用于追加的文件。如果该文件不存在,会创建该文件
-
‘x’ 创建一个新文件。如果文件存在,则失败
-
‘+’ 打开一个文件进行更新
我们还可以指定以文本模式“t”、默认模式或二进制模式“b”打开文件。让我们看看如何使用简单的语句复制图像文件 dataquest_logo.png:
- with open('dataquest_logo.png', 'rb') as rf:
- with open('data_quest_logo_copy.png', 'wb') as wf:
- for b in rf:
- wf.write(b)
上面的代码复制 Dataquest 徽标图像并将其存储在同一路径中。’rb’ 模式以二进制模式打开文件并进行读取,而 ‘wb’ 模式以文本模式打开文件以并行写入
读取文本文件
在 Python 中有多种读取文本文件的方法,下面我们介绍一些读取文本文件内容的有用方法
到目前为止,我们已经了解到可以使用 read()
方法读取文件的全部内容。如果我们只想从文本文件中读取几个字节怎么办,可以在 read()
方法中指定字节数。让我们尝试一下:
- with open('zen_of_python.txt') as f:
- print(f.read(17))
Output:
The Zen of Python
上面的简单代码读取 zen_of_python.txt 文件的前 17 个字节并将它们打印出来
有时一次读取一行文本文件的内容更有意义,在这种情况下,我们可以使用 readline() 方法
- with open('zen_of_python.txt') as f:
- print(f.readline())
Output:
The Zen of Python, by Tim Peters
上面的代码返回文件的第一行,如果我们再次调用该方法,它将返回文件中的第二行等,如下:
- with open('zen_of_python.txt') as f:
- print(f.readline())
- print(f.readline())
- print(f.readline())
- print(f.readline())
Output:
- The Zen of Python, by Tim Peters
-
- Beautiful is better than ugly.
-
- Explicit is better than implicit.
这种有用的方法可以帮助我们以增量方式读取整个文件。
以下代码通过逐行迭代来输出整个文件,直到跟踪我们正在读取或写入文件的位置的文件指针到达文件末尾。当 readline()
方法到达文件末尾时,它返回一个空字符串
- with open('zen_of_python.txt') as f:
- line = f.readline()
- while line:
- print(line, end='')
- line = f.readline()
Output:
- The Zen of Python, by Tim Peters
-
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than *right* now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
上面的代码在 while
循环之外读取文件的第一行并将其分配给 line
变量。在 while
循环中,它打印存储在 line
变量中的字符串,然后读取文件的下一行。while
循环迭代该过程,直到 readline()
方法返回一个空字符串。空字符串在 while
循环中的计算结果为 False
,因此迭代过程终止
读取文本文件的另一个有用方法是 readlines()
方法,将此方法应用于文件对象会返回包含文件每一行的字符串列表
- with open('zen_of_python.txt') as f:
- lines = f.readlines()
让我们检查 lines 变量的数据类型,然后打印它:
- print(type(lines))
- print(lines)
Output:
- <class 'list'>
- ['The Zen of Python, by Tim Peters\n', '\n', 'Beaut...]
它是一个字符串列表,其中列表中的每个项目都是文本文件的一行,“\n` 转义字符表示文件中的新行。此外,我们可以通过索引或切片操作访问列表中的每个项目:
- print(lines)
- print(lines[3:5])
- print(lines[-1])
Output:
- ['The Zen of Python, by Tim Peters\n', '\n', 'Beautiful is better than ugly.\n', ... -- let's do more of those!"]
- ['Explicit is better than implicit.\n', 'Simple is better than complex.\n']
- Namespaces are one honking great idea -- let's do more of those!
读取 CSV 文件
到目前为止,我们已经学会了如何使用常规文本文件。但是有时数据采用 CSV 格式,数据专业人员通常会检索所需信息并操作 CSV 文件的内容
接下来我们将使用 CSV 模块,CSV 模块提供了有用的方法来读取存储在 CSV 文件中的逗号分隔值。我们现在就尝试一下
- import csv
- with open('chocolate.csv') as f:
- reader = csv.reader(f, delimiter=',')
- for row in reader:
- print(row)
Output:
- ['Company', 'Bean Origin or Bar Name', 'REF', 'Review Date', 'Cocoa Percent', 'Company Location', 'Rating', 'Bean Type', 'Country of Origin']
- ['A. Morin', 'Agua Grande', '1876', '2016', '63%', 'France', '3.75', 'Â\xa0', 'Sao Tome']
- ['A. Morin', 'Kpime', '1676', '2015', '70%', 'France', '2.75', 'Â\xa0', 'Togo']
- ['A. Morin', 'Atsane', '1676', '2015', '70%', 'France', '3', 'Â\xa0', 'Togo']
- ['A. Morin', 'Akata', '1680', '2015', '70%', 'France', '3.5', 'Â\xa0', 'Togo']
- ...
CSV 文件的每一行形成一个列表,其中每个项目都可以轻松的被访问,如下所示:
- import csv
- with open('chocolate.csv') as f:
- reader = csv.reader(f, delimiter=',')
- for row in reader:
- print("The {} company is located in {}.".format(row[0], row[5]))
Output:
- The Company company is located in Company Location.
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The Acalli company is located in U.S.A..
- The Acalli company is located in U.S.A..
- The Adi company is located in Fiji.
- ...
很多时候,使用列的名称而不是使用它们的索引,这通常对专业人员来说更方便。在这种情况下,我们不使用 reader()
方法,而是使用返回字典对象集合的 DictReader()
方法
- import csv
- with open('chocolate.csv') as f:
- dict_reader = csv.DictReader(f, delimiter=',')
- for row in dict_reader:
- print("The {} company is located in {}.".format(row['Company'], row['Company Location']))
Output:
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The A. Morin company is located in France.
- The Acalli company is located in U.S.A..
- The Acalli company is located in U.S.A..
- The Adi company is located in Fiji.
- ...
读取 JSON 文件
我们主要用于存储和交换数据的另一种流行文件格式是 JSON,JSON 代表 JavaScript Object Notation,允许我们使用逗号分隔的键值对存储数据
接下来我们将加载一个 JSON 文件并将其作为 JSON 对象使用,而不是作为文本文件,为此我们需要导入 JSON 模块。然后在 with
上下文管理器中,我们使用了属于 json 对象的 load()
方法,它加载文件的内容并将其作为字典存储在上下文变量中。
- import json
- with open('movie.json') as f:
- content = json.load(f)
- print(content)
Output:
{'Title': 'Bicentennial Man', 'Release Date': 'Dec 17 1999', 'MPAA Rating': 'PG', 'Running Time min': 132, 'Distributor': 'Walt Disney Pictures', 'Source': 'Based on Book/Short Story', 'Major Genre': 'Drama', 'Creative Type': 'Science Fiction', 'Director': 'Chris Columbus', 'Rotten Tomatoes Rating': 38, 'IMDB Rating': 6.4, 'IMDB Votes': 28827}
让我们检查内容变量的数据类型:
print(type(content))
Output:
<class 'dict'>
它的数据类型是字典,因此我们可以方便的从中提取数据
print('{} directed by {}'.format(content['Title'], content['Director']))
Output:
Bicentennial Man directed by Chris Columbus
总结
今天我们讨论了 Python 中的文件处理,重点是读取文件的内容。我们了解了 open()
内置函数、with
上下文管理器,以及如何读取文本、CSV 和 JSON 等常见文件类型。