"Learning Python with You Hand in Hand" 31-File Opening

In the last article "Learning Python with You Hand in Hand" 30-Module , we learned how to call functions in other files by importing modules. This is the first time we have implemented cross-program or cross-file operations.

Next, we will further learn how to manipulate other files through Python, including opening files, reading files, closing files, writing files, and storing files. Python is very simple to process files, which is why Python is very popular in the field of text and file processing.

In order to facilitate the explanation and demonstration of today and the next few articles, we have to make a text file by ourselves as a sample file that runs through our next few articles. You can make the content of the text file at will. I will use part of the title of the series of articles "Learning Python with You" as the content to create a text file contents.txt, which has the content written:

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

You can download this document and the example program of this article by following the "Yishuo Python" official account and replying to "Hand 31".

Below, I will introduce the basic operations of Python processing files.

1. File path

To read a file, you must first know where the file is.

a, the same folder

Python will look for the folder where the current program is located by default. If the program file and the target file are in the same folder, then there is no need to tell Python the path of the target file, just use the file name contents.txt directly, and Python can read it.

b, subordinate folders

If the target file is at the lower level (including the lower level or multiple levels) of the folder where the program file is located, "relative path" can be used.

For example, the folder where the program file is located is python, and the target file is in the text folder in the lesson folder in the python folder. At this time, the relative path of the target file is "lesson/text/contents.txt". At this time, not only tell the Python target file what the file name is, but also tell the location of the Python target file relative to the program file.

It should be noted here that the file path in the Windows system uses a backslash "\" to distinguish different levels of folders, but in a Python program, a slash "/" can be used to indicate. If you also want to use a backslash to indicate it, you should be careful not to use the backslash "\" directly, because the backslash in Python means escape.

If there is a folder starting with t or n in the file path (such as C:\python\new\text.txt), when combined with a backslash, \n and \t will be interpreted by Python as return lines or tabs of. Therefore, when using backslashes to display file addresses, it is best to use backslashes to escape each backslash in the path to avoid accidental escapes (such as C:\\python\\new\\ text.txt).

c, other folders

If the target file is in the upper level of the program file or in another folder, then you need to use the "absolute path". The absolute path is the complete address and exact location of our file storage, which is the same as the address in the address bar.

At this time, tell Python that the path of the target file is "D:\study\python\contents.txt".

One thing to remember is that absolute paths can be used instead of relative paths, but relative paths cannot be used instead of absolute paths.

2. Open the file

Once you know the file location, you can use Python's built-in function open() to open the file.

a、open()

The required parameter in open() is the file name (including path) of the target file. The meaning of other optional parameters and the complete syntax format are:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

among them:

file: required, file path (relative or absolute path)

mode: optional, file opening mode

buffering: set buffering

encoding: generally use utf8

errors: error level

newline: distinguish newline characters

closefd: file parameter type passed in

opener: Set a custom opener, the return value of the opener must be an open file descriptor

b, mode parameter

Among the optional parameters, the most important is the file opening mode mode, the default value is "r", which means it is opened in read-only mode. Other common modes include:

mode

description

r

Read only mode (default).

w

Write only mode, create a new file (clear the data in the file with the same name under the path).

x

Write only mode, create a new file, but if there is a path with the same name, the creation will fail.

a

Add to an existing file (create if it does not exist).

r+

Read and write mode.

b

The mode of the binary file is added to other modes (such as "rb" or "wb").

t

The text mode of the file (automatically decode the bytes into Unicode) can be added to other modes (such as "rt" or "xt").

In this article, we will select several of the more commonly used modes as examples. For other file opening modes not involved, you can write your own examples for testing.

c, encoding parameter

Another parameter that may be used is encoding. Encoding means encoding, that is, when the encoding format of the file we want to open is inconsistent with the encoding format used by our compiler, we need to add a parameter item, generally use "encoding ='utf-8'" as a keyword parameter to increase In the open() function.

When there are only English letters, numbers, and characters in our target file, we generally don't need to add this parameter. If the target file contains Chinese characters, not only must use this parameter, but also pay attention to when we make the target file, the encoding mode must be changed to UTF-8 before saving, otherwise it may not be decoded. At this time, even if "encoding ='utf-8'" is used, the target file itself cannot be opened because it is not in UTF-8 format.

 

image

d, open the file

After learning how to open the file open() function, we can write the following code to open our target file:

In [1]: path = 'lesson/text/contents.txt'   # 相对路径,其他方式请大家自行练习
        file_object = open(path, encoding = 'utf-8')   # 默认mode = 'r'

Since relative paths and absolute paths are generally relatively long, it is customary to assign the path to the path or filename variable, and then use it as a function of open(). Of course, the path can also be directly used as a parameter, especially when the file name of the target file is used directly, it can be directly used as a parameter of open(). It should be noted that whether you use a path or a file name, it must be written in the form of a string.

Can we read it after opening the file?

Let's print the file file_object we just opened to see if it is the content of the target file:

In [2]: path = 'lesson/text/contents.txt'
        file_object = open(path, encoding = 'utf-8')
        print(file_object)
Out[2]: <_io.TextIOWrapper name='lesson/text/contents.txt' mode='r' encoding='utf-8'>

As you can see, the returned result is not the content of the target file, but an iterator. In other words, after the open() function opens the target file, it only returns a piece of data that can be used to traverse. This will be experienced when we read the file line by line in the next article, and the target file The content needs to be read in other ways.

In the next article, we will focus on several methods for reading files, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

"Learning Python with You Hand in Hand" 24-Collection

"Learning Python with You Hand in Hand" 25-List Comprehension

"Learning Python with You Hand in Hand" 26-Custom Functions

"Learning Python with You Hand in Hand" 27-Parameters of Custom Functions

"Learning Python with You Hand in Hand" 28-the return value of a custom function

"Learning Python with You Hand in Hand" 29-Anonymous Functions

"Learning Python with You Hand in Hand" 30-Module

For Fans: Follow the "also said Python" public account, reply "Hand 31", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/111303856