ファイルはどこにでもあり、どのプログラミング言語を使用するかに関係なく、ファイルの処理はすべてのプログラマーにとって不可欠です
ファイル処理は、ファイルを作成し、データを書き込み、 Python には、さまざまな種類のファイルを処理するためのパッケージが豊富に用意されているため、ファイル処理作業をより簡単かつ便利に完了できます。
この記事の概要:
ファイルの内容にアクセスする前に、ファイルを開く必要があります。 Python には、さまざまなモードでファイルを開くのに役立つ組み込み関数が用意されています。 open() 関数は、ファイル名とモードという 2 つの基本パラメータを受け入れます。
デフォルトのモードは「r」で、ファイルを読み取り専用モードで開きます。これらのモードは、ファイルにアクセスする方法とその内容を操作する方法を定義します。 open() 関数にはいくつかの異なるモードがあり、これについては後ほど 1 つずつ説明します。 #
f = open('zen_of_python.txt', 'r') print(f.read()) f.close()
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 open('zen_of_python.txt') as f: print(f.read())
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. ...
print("Filename is '{}'.".format(f.name)) if f.closed: print("File is closed.") else: print("File isn't closed.")
Filename is 'zen_of_python.txt'. File is closed.
f.read()
'r' は読み取り専用ファイルを開きます
'w' は読み取り専用ファイルを開きます書き込み入力。ファイルが存在する場合は上書きされ、存在しない場合は新しいファイルが作成されます。
--------------------------------------------------------------------------- ValueErrorTraceback (most recent call last) ~AppDataLocalTemp/ipykernel_9828/3059900045.py in <module> ----> 1 f.read() ValueError: I/O operation on closed file.
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)
with open('zen_of_python.txt') as f: print(f.read(17))
The Zen of Python
with open('zen_of_python.txt') as f: print(f.readline())
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())
以下代码通过逐行迭代来输出整个文件,直到跟踪我们正在读取或写入文件的位置的文件指针到达文件末尾。当 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 Petersn', 'n', 'Beaut...]
它是一个字符串列表,其中列表中的每个项目都是文本文件的一行,``n` 转义字符表示文件中的新行。此外,我们可以通过索引或切片操作访问列表中的每个项目:
print(lines) print(lines[3:5]) print(lines[-1])
Output:
['The Zen of Python, by Tim Petersn', '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 文件中的逗号分隔值。我们现在就尝试一下
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 代表 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 等常见文件类型。
好了,这就是今天分享的全部内容,喜欢就点个赞吧~
以上がPython でのファイルの読み取りに関するすべての知識を 1 つの記事で取得しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。