Life is short. I’m going to go with Python

The portal

Little White Learning Python (1) : Introduction

Python (2) : Basic data types

Python (3) : Basic data types

Python (4) : Variable base operations

Python (5) : Basic operators (1)

Python (6) : Basic operators

Basic Flow control (part 1)

Basic Flow control (part 2)

Python (9) : Basic data structures

Python (10) : Basic data structures

Python (11) : Basic Data Structures (tuples)

Python (12) : Basic data structures (dictionaries)

Python (13) : Basic data structures (dictionaries)

Basic Data Structures (Collections) (part 1)

Basic Data Structures (Sets) (2)

Python (16) : Basic data types (functions)

Python (17) : Basic data types (functions)

Absolute path and relative path

Before introducing file operations, let’s introduce two concepts, absolute and relative paths.

Baidu first look at baidu’s explanation:

  • Absolute path: indicates the absolute location in a directory. The path directly reaches the destination location, usually starting from the drive letter. The complete path that describes the location of the file is the absolute path.
  • Relative path: Relative path refers to the relationship between the path of this file and other files (or folders).

I don’t know if you understand, but IF you don’t, LET me give you one more chestnut to deepen your understanding.

An absolute path

For example, if we want to describe the absolute path to demo. py, we would say: F:/project/python-learning/base-data-def/ demo.py.

Relative paths

A relative path is a path that describes the current location relative to the target location. For example, we currently have a path F:/project/python-learning/. We still need to describe the Demo. Then its relative path is./base-data-def/ demo.py.

Open the file

Python gives us the built-in function open() to open files.

Common syntax:

open(file, mode='r')Copy the code

Complete syntax:

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

Parameter Description:

  • File: Required, file path (relative or absolute).
  • Mode: indicates the file opening mode
  • Buffering: Sets the buffer
  • Encoding: UtF-8 is commonly used
  • Errors: indicates the error level
  • Newline: distinguishes the newline character
  • Closefd: Type of the file parameter passed in

Common values of the mode parameter:

model describe
t Text mode (default).
x In write mode, create a new file. If the file already exists, an error will be reported.
b Binary mode.
+ Open a file for update (readable and writable).
r Open the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for read-only use. The file pointer will be placed at the beginning of the file. This is the default mode. Generally used for non-text files such as pictures.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ To open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. Generally used for non-text files such as pictures.
w Opening a file is for writing only. If the file already exists, the file is opened and edited from the beginning, that is, the original content is deleted. If the file does not exist, create a new one.
wb Open a file in binary format only for writing. If the file already exists, the file is opened and edited from the beginning, that is, the original content is deleted. If the file does not exist, create a new one. Generally used for non-text files such as pictures.
w+ Open a file for reading and writing. If the file already exists, the file is opened and edited from the beginning, that is, the original content is deleted. If the file does not exist, create a new one.
wb+ To open a file in binary format for reading and writing. If the file already exists, the file is opened and edited from the beginning, that is, the original content is deleted. If the file does not exist, create a new one. Generally used for non-text files such as pictures.
a Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
ab Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Files open in append mode. If the file does not exist, create a new file for reading and writing.
ab+ Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

Let’s start with our first example:

str1 = open('F:/project/python-learning/base-data-def/Demo.py', mode='r').read()
print(str1)Copy the code

I will not post the print results, but normally print the sample code of our previous several articles.

Coding format

Depending on the encoding format, files can be divided into text characters and binary bytes.

We see text characters every day, but text characters are converted to binary bytes when saving the computer, and this is where encoding comes in.

Let’s look at an example diagram of the transformation:

It is worth noting that in Python3, the default encoding for files is utf-8, and common encodings for text characters are ASCII and Unicode.

Having said that, let’s look at an example code:

Encode ('utf-8') print(type(a)) print(a.decode('utf-8'))Copy the code

The print result is as follows:

<class 'STR '> <class 'bytes'> Study hard and make progress every dayCopy the code

As you can see, after we encode the string encode(), the type becomes byte.

What if we use GBK to decode the a above?

print(a.decode('gbk'))Copy the code

The results are as follows:

Traceback (most recent call last):
  File "F:/project/python-learning/base-file/Demo.py", line 10, in <module>
    print(a.decode('gbk'))
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8a in position 26: incomplete multibyte sequenceCopy the code

It tells us that GBK cannot be used for decoding operations.

This is actually very easy to understand, for example, we translate Chinese into English (encoding), and then we want to translate English back to Chinese (decoding) through the Japanese translator, then the Japanese translator will definitely scold you are mentally ill.

OS module

Previously we described manipulating files through built-in functions, but we can also manipulate files through OS modules that are much simpler.

The OS module is related to the operating system.

To demonstrate, create a test.txt file.

First, we open this file:

import os
os.chdir('F:/project')
file = open('test.txt')Copy the code

Read this file and print:

print(file.read())Copy the code

The results are as follows:

Wechat official account: Geek ExcavatorCopy the code

Then we’ll add something more below:

File. Write (' pay attention to the public account, good good study, day day up ')Copy the code

Then I found the execution error:

Traceback (most recent call last): File "F:/project/python-learning/base-file/ demo. py", line 17, in <module> file.write(' 解 决 数 字, 数 据, 数 据, 数 据, 数 据, 数 据, 数 据, 数 据, 数 据 UnsupportedOperation: not writableCopy the code

From the error message, we can see that the problem is our current read permission, because we read the read-only permission, cannot write, so slightly modify the above read file code:

Import OS os.chdir('F:/project') file = open('test.txt', mode='a+') file.write(' \n 中 文 中, 中 文 中, 中 文 中 ') import OS os.chdir('F:/project') file = open('test.txt', mode='a+') file.write(' \n 中 文 中, 中 文 中, 中 文 中 ')Copy the code

After executing, let’s take a look at our test file:

Write succeeded.

Let’s test an interesting thing. What happens if we read the same file twice?

import os
os.chdir('F:/project')
file = open('test.txt')
print(file.read())
print(file.read())Copy the code

The print result is as follows:

Wechat official account: Geek Excavator concern official account, study hard, make progress every dayCopy the code

Why do we only show it once when we print it twice in the code?

Because read() reads everything, and after that, the cursor is at the end, and after that, you can’t read anything.

Well, that’s the end of this article, and I hope you can practice with some sample code.

The sample code

All of the code in this series will be available on Github and Gitee.

Example code -Github

Example code -Gitee