Python --- File operations

Table of contents

Preface

1. open() function

1.Read-only mode r

2. Write-only mode w

3.Append mode a

2. Operation of other files

1.Python operates binary

2.Python operates json files

3. Close the file

4. Context Manager

5. File pointer position


Preface

In actual operations, we usually need to write data to local files or read data from local files. As Python enthusiasts, we must master the use of Python language to operate local files.

Local file operation steps:

  1. Find the location of the file
  2. open a file
  3. Operation files
  4. close file

1. open() function

file: Open file location (path)
mode: Specifies the permissions to operate the file (default read-only permissions)
encoding: Specify encoding utf-8 to solve the problem of Chinese garbled characters

File mode

model illustrate pointer initial position if the file does not exist
r Open file as read-only Beginning of file Report an error
w Open a file for writing. Note: This mode is written from scratch and will overwrite existing content. Beginning of file create
a Like w, it writes to a file. The difference is that it does not write from the beginning, but continues after the existing file. End of file create
x If the file already exists, an error will be reported. If the file does not exist, it will be created and then written. It is safer than w mode. create
b Operate files in bytes type, generally used in combination with the previous mode
rb Basically the same as r, except that it opens the file in binary format Beginning of file Report an error
wb Basically the same as w, the difference is that the file is opened in binary format Beginning of file create
ab Basically the same as a, the difference is that the file is opened in binary format End of file create

In addition, there are r+, w+, a+, rb+, wb+, and ab+ corresponding to them respectively. The difference is that these are all readable and writable operations. Please try it yourself for details.

1.Read-only mode r

method describe
f.readable() Determine whether it is readable
f.read(n)

Read all, n is a character in python

n can set how much content to read by yourself. If it is not set or set to a negative value, all the content will be read.

f.readline() Read line by line, including\n
f.readines Read all, the return value is a list, including\n

data.txt

hello
world
cheng xu yuan

(1)f.readable()

Determine whether it is readable and return a Boolean value

f = open('data.txt', mode='r', encoding='utf-8')
if f.readable():
    print('可读')
else:
    print('不可读')

operation result:

(2)f.read(n)

Here n can set how much content to read by yourself. If it is not set or set to a negative value, all the content will be read.

if f.readable():   
    f = open('data.txt', mode='r', encoding='utf-8')
    print(f.read(8))

 operation result:

(3)f.readline()

Read one line of content from the file. The newline character is '\n'. Repeatedly entering this command will start reading from the next line.

if f.readable():
    f = open('data.txt', mode='r', encoding='utf-8')
    print(f.readline(), end='')
    print(f.readline(), end='')

operation result:

Observing carefully, we can find that when f.readline() is printed once, it only outputs one line, and the pointer moves to the beginning of the next line. The last line of output is a null character, indicating that the pointer has reached the end of the file and will not automatically return to the beginning.

Each time a line of content is output, it will automatically output a \n. We can add end='' at the end, which means that its default ending is '\n', and we change it to a null character.

(4)f.readlines()

Save each line in the file as an element in a list, and the returned value is this list. It will read all the contents of the file into the list at once. One advantage is that it is very convenient to access the contents.

if f.readable():
    f = open('data.txt', mode='r', encoding='utf-8')
    print(f.readlines())

operation result:

Notice:

  • r mode, an error will be reported when the file does not exist
  • Reading is irreversible

2. Write-only mode w

method describe
f.writable() Determine whether it is writable
f.write(str) Write content, the return value is the length of the written string
f.writelines(seq) Write multiple lines, but you need to add newlines yourself

(1)f.write(str)

Used to write string or byte type data to a file. This command can be repeated multiple times, but it only operates in computer memory. Only when the file is closed (not required in the with statement) will it be saved to the hard disk.

with open('data.txt',mode='w',encoding='utf-8') as file:
    f = (file.write('很美'))

print(type(f),f,sep='\n')

with open('data.txt',mode='r',encoding='utf-8') as file:
    print(file.read())

 operation result:

Notice:

  • w mode, creates a file when it does not exist
  • Overwrite when writing again

3.Append mode a

Notice:

  • a mode, creates a file when it does not exist
  • Write again as append

4.b

b mode

  • Binary mode: generally used to read files such as pictures and videos

  • Note: When reading and writing, the bytes type is read and written, so the result is a bytes object instead of a string. When reading and writing, you need to specify the character encoding.

s='this is a test'
b=bytes(s,encoding='utf-8')
f=open('t2.txt','w')
f.write(s)
f.write(b)

s='this is a test'
b=bytes(s,encoding='utf-8')
f=open('t3.txt','wb')  # wb 用于bytes类型
f.write(b)
f.close()

5.+

  • w+ mode: The file content will be cleared before reading and writing.

  • a+ mode: always write at the end of the file

  • r+ mode: read and write mode, more operations can be achieved with the seek() tell() method

2. Operation of other files

1.Python operates binary

In Python, use wb mode to write binary data.

2.Python operates json files

method describe
json.loads() Convert json to dictionary (applicable to statements)
json.dumps() Convert dictionary to json (applicable to statements)
json.load() Convert json to dictionary (applicable to files)
json.dump() Convert dictionary to json (used in files)

3. Close the file

It should be noted that after the file is opened, the file must be closed through the f.close() statement to release resources.

4. Context Manager

The with keyword is used in Python's context manager mechanism. In order to prevent exceptions or errors in the operation process of file opening methods such as open, or forgetting to execute the close method in the end, the file is closed abnormally, etc., which may lead to file leakage and damage. Python provides the with context manager mechanism to ensure that the file will be closed normally. Under its management, there is no need to write a close statement. The rest of the operations are the same as open().

f = open('data.txt', 'w')
f.write("cheng xu")
f.close()  # 关闭文件

 Use context manager:

with open('data.txt', 'w') as f:
    f.write("cheng xu")

5. File pointer position

During the file reading and writing operations, we found that the file pointer has a fixed position according to our opening method and the execution of the reading and writing commands. In this way, we cannot use it as we like, so we need to be able to control the pointer ourselves. s position.

method describe
f.tell() File location
f.seek(offset,whence)

1.tell()

Returns the current position of the file read-write pointer. This position is  the number of bytes  from the beginning of the file , not the number of characters.

with open('data.txt',mode='w',encoding='utf-8') as file:
    file.write('你好')
    print(file.tell())
    file.write('呀')
    print(file.tell())

operation result:

From here we can also find that Chinese characters occupy three bytes.

2.f.seek(offset,whence)

Used to specify the position of the pointer. It has two parameters. Let’s introduce the second parameter whence first. It has three fixed options, namely 0, 1, and 2.

whence
0 Offset from the beginning of the file
1 Offset from current location
2 offset from end of file

The first parameter is the offset, which is the number of bytes that need to be moved from the selected position. It is easy to understand. Please see the example: (Insert the characters 'men' in the middle of 'Hello')

with open('data.txt',mode='r+',encoding='utf-8') as file:
    file.write('你好')
    file.seek(0, 0)
    print(file.read())
    file.seek(3, 0)
    old=file.read()
    file.seek(3, 0)
    file.write('们')
    file.write(old)
    file.seek(0, 0)
    print(file.read())

operation result:

 

Guess you like

Origin blog.csdn.net/m0_63636799/article/details/130169562