Python programming basics: file operations

1. File path

The location where the file is saved is called a path. There are two main types of paths when defining them: absolute paths and relative paths.

1. Absolute path

The absolute path refers to describing the storage location of the file starting from the name of the drive where the file is located, which is often called C drive, D drive, F drive, etc. The common absolute path expressions are as follows:

C:\documents\python\1.py

Where '\' is the separator between directories and files. When describing the path of a file in python, you need to use a string, but in a string, '' is an escape sequence character, so when using it, you need to Use two '' to write, such as:

C:\\documents\\python\\1.py

If you want to use a single '', you can add r in front of the path to cancel the escaping feature of '' in subsequent strings, such as:

r "C:\documents\python\1.py"

2. Relative path

The relative path refers to the location information describing the file starting from the current working directory. Each program has a current working directory when it is running. Generally speaking, the current directory defaults to the installation directory of the application. You can view and modify the current working directory. Use the os library that comes with Python to set it up.
View the current directory:

import os
os.getcwd()

Modify the current working directory to 'D:\python':

os.chdir('D:\\python')

At this time, if there is a folder named python in the current directory, and there is a 1.py file in it, the relative path of the file is expressed as:

\\python\\1.py

Note: '' is used as the separator between directories and files in Windows systems, and '/' is used as the separator in other operating systems.

2. File operations

There are three main operations on files: opening files, reading and writing files, and closing files.

1. Opening of files

Files are generally stored in external memory. When operating, they need to be transferred into memory first, and then processed by the CPU. This transfer process is the file opening process. Use the open command in Python to open a file and generate a file object. The operation on the file object is the operation on the file. The syntax format is as follows:

文件对象 = open(文件路径字符串, 模式字符)

The file path can be an absolute path or a relative path. Mode characters are mainly used to specify the type of file to open and the way to operate the file. Common mode characters are as follows:

pattern character file type Operation method When the file does not exist Whether to cover
‘r’ text file read-only file Report an error no
‘r+’ text file Readable and writable Report an error yes
‘w’ text file Only writable files create a new file yes
‘w+’ text file Readable and writable create a new file yes
‘a’ text file Only writable files create a new file No, write additionally at EOF
‘a+’ text file Readable and writable create a new file No, write additionally at EOF
‘rb’ binary file read-only file Report an error no
‘rb+’ binary file Readable and writable Report an error yes
‘wb’ binary file Only writable files create a new file yes
‘wb+’ binary file Readable and writable create a new file yes
‘ab’ binary file Only writable files create a new file No, write additionally at EOF
‘ab+’ binary file Readable and writable create a new file No, write additionally at EOF

In the above table, text files mainly refer to files that only contain basic text characters and do not contain format information such as font, size, color, etc. The most common file files are .txt and .py, etc. In addition to text files, other files such as .doc, .xls, etc. are all binary files. The operation of text files is relatively simple, but the operation of binary files is more complicated and requires the help of different libraries. The following introduction focuses on the operation of text files.

2. Closing of files

After using open to open the file, the file is transferred into the memory. At this time, other applications cannot operate the file. When the read and write operations are completed, the file needs to be saved to external storage, that is, its updated content is synchronized to the external storage. In addition, the space it occupies in the memory also needs to be released so that other applications can operate the file. This process is called file closing.
To close a file in python, you need to use the close() method of the file object. The syntax format is as follows:

文件对象.close()

In the above content, the file object is the content associated with the file. Any operation on the file needs to be implemented by calling the file object. When closed using close(), no operations are allowed on the file object. .

3. Writing files

There is a 1.txt file under the current path. To write content in the file, there are two main writing methods: write() method and writelines() method.

write() method

The write() method writes the specified string to the current insertion point position of the file. When writing multiple times, there will be no separator between the newly written string and the original string. At the same time, each write will return the write The number of characters, its syntax format is as follows:

文件对象.write(字符串内容)

Insert image description here
Insert image description here
writelines() method
The writelines() method can accept multiple strings as parameters in a sequence and write multiple strings at one time. Its syntax format is as follows:

文件对象.writelines(字符串序列)

Insert image description here

4. Reading of files

Similar to writing content, python defines three methods to complete reading files, namely read(), readline() and readlines() methods.

read() method
The read() method reads all the contents of the file and returns it as a string. Its syntax is as follows:

字符串变量 = 文件对象.read()

Insert image description here
readline() method
The readline() method reads the current line in the file and returns it as a string. If you read multiple times continuously, you can read the contents of each line in order. The syntax format is as follows:

字符串变量 = 文件对象.readline()

Insert image description here
readlines() method
The readlines() method reads all the contents of the file and returns it as a list. Each line of content is an element of the list. The syntax format is as follows:

字符串变量 = 文件对象.readlines()

Insert image description here

3. CSV file operation

CSV files can be understood as files that store table data in plain text separated by comma delimiters or other simple characters. This file type can generally be opened with programs such as Notepad and Excel. The score.csv file is opened using Notepad and Excel respectively. The content is as follows:
Insert image description here
Insert image description here
For CSV files, Python specifically provides a built-in module of the same name for reading and writing operations. When using it, a reader object and a writer object need to be defined.

1. Opening CSV files

Like text files, CSV files can be opened directly with the open command, but it is troublesome to use the close() method every time. Therefore, the with statement is introduced to open the file. The file will be automatically closed after each file operation. Its syntax The format is as follows:

with open(文件路径, 模式字符) as 文件对象名:
    文件操作语句

Insert image description here

2. Reading CSV files

To read a CSV file, you need to use the csv module to first create a reader object, and then iterate through the reader object to obtain each line in the csv file. Take score.csv as an example: In the above example, the content of each line of the csv file
Insert image description here
is Output in the form of a list, in which the encoding mode is set to "encoding='utf-8'" due to the presence of Chinese characters.

3. Writing CSV files

Similar to reading a file, writing content requires creating a writer() object. There are two writing methods: writerow() method and writerows() method.

writerow() method
The writerow() method is used to write a row of data stored in the list to a file, such as ['10153450111','67','89','76'] and ['10153450112','88',' 67','92'] written to score.csv.
Insert image description here
Insert image description here
You can see that blank lines appear between the written records. When opening the file, add a parameter newline= '' to indicate that blank lines will not be inserted when writing content.
Insert image description here
Insert image description here
writerows() method
The writerow() method can write each element of the sequence as a row of content into the CSV file at once, for example, [['10153450111','67','89','76'],['10153450112' ,'88','67','92']] is written to score.csv.
Insert image description here
Similarly, adding a parameter newline='' when opening the file can indicate that blank lines will not be inserted when writing content.

Guess you like

Origin blog.csdn.net/weixin_42051846/article/details/131866942