Files are everywhere, no matter which programming language we use, processing files is essential for every programmer
File processing is a A process for creating files, writing data, and reading data from them. Python has a wealth of packages for processing different file types, making it easier and more convenient for us to complete file processing work
This article Outline:
Before accessing the contents of the file, we need to open the file. Python provides a built-in function that helps us open files in different modes. The open() function accepts two basic parameters: file name and mode
The default mode is "r", which opens the file in read-only mode. These modes define how we access a file and how we manipulate its contents. The open() function provides several different modes, which we will discuss one by one later.
Let's use the 'Zen of Python' file to discuss and learn later
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. ...
In the above code, the open() function opens the text file in read-only mode, which allows us to get information from the file without changing it. In the first line, the output of the open() function is assigned to an object f that represents the text file. In the second line, we use the read() method to read the entire file and print its contents. The close() method is in the last line. Close the file. It is important to note that we must always close open files after processing them to free up our computer resources and avoid throwing exceptions
In Python, we can use the with context manager to ensure that the program is released after the file is closed The resource used, even if an exception occurs
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. ...
The above code creates a context using the with statement and binds it to the variable f. All file object methods can pass This variable accesses the file object. The read() method reads the entire file on the second line and then uses the print() function to output the file content
When the program reaches the end of the with statement block context, it closes the file to release resources and ensure that other programs They can be called normally. Usually when we deal with objects that no longer need to be used and need to be closed immediately (such as files, databases and network connections), it is strongly recommended to use the with statement
It should be noted here that even after exiting the with context manager After the block, we can also access the f variable, but the file is closed. Let's try some file object properties and see if the variable still exists and is accessible:
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.
But at this point it is not possible to read from or write to the file Yes, when a file is closed, any attempt to access its contents will result in the following error:
f.read()
Output:
--------------------------------------------------------------------------- ValueErrorTraceback (most recent call last) ~AppDataLocalTemp/ipykernel_9828/3059900045.py in <module> ----> 1 f.read() ValueError: I/O operation on closed file.
As we discussed earlier As mentioned, we need to specify the mode when opening the file. The following table shows the different file modes in Python:
Mode description
We can also specify to open the file in text mode "t", default mode, or binary mode "b". Let’s see how to copy the image file dataquest_logo.png using a simple statement:
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)
The above code copies the Dataquest logo image and stores it in the same path. 'rb' mode opens the file in binary mode for reading, while 'wb' mode opens the file in text mode for parallel writing
There are many in Python Methods for reading text files, below we introduce some useful methods for reading the contents of text files
So far, we have learned that you can use the read() method to read the entire contents of a file. What if we only want to read a few bytes from the text file, we can specify the number of bytes in the read() method. Let’s try it out:
with open('zen_of_python.txt') as f: print(f.read(17))
Output:
The Zen of Python
The simple code above reads the first 17 bytes of the zen_of_python.txt file and prints them out
sometimes once It makes more sense to read the content of a text file in one line. In this case, we can use the readline() method
with open('zen_of_python.txt') as f: print(f.readline())
Output:
The Zen of Python, by Tim Peters
The above code returns the first line of the file, If we call the method again, it will return the second line in the file, etc., as follows:
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.
This useful method can help us read incrementally the entire file.
以下代码通过逐行迭代来输出整个文件,直到跟踪我们正在读取或写入文件的位置的文件指针到达文件末尾。当 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 等常见文件类型。
好了,这就是今天分享的全部内容,喜欢就点个赞吧~
The above is the detailed content of Get all the knowledge about reading files in Python in one article. For more information, please follow other related articles on the PHP Chinese website!