Python minimal core: files

A few pieces of logic are written first:

  • The open function must be used first , after the file is opened, the subsequent write and read operations
  • Need to define the purpose of the file in the open function ( set the parameters of the open function ), such as reading, writing, reading, writing, appending, etc.
  • The position of the pointer directly affects the target content

This article mainly summarizes from the two major directions of basic opening, writing, reading and file operations.

1. A brief overview of file opening, writing, and reading

open function

open()Function is a built-in function of Python, used to create a file object , remember: with the file object, related methods can be called to read and write .
The basic usage is: fileObject = open(xx, x)
Here, xx represents the file to be opened, and x refers to the parameter.
(Open files are omitted below)

open(, r): read only, do not create
open(, r+): read + write, do not create
open(, w): write only
open(, w+): write + read
open(, a): write in append mode ( No coverage)
open(, a+): write in append mode (no coverage) + read
that is, the plus sign '+'represents the additional mode.
Insert picture description here
Note:

  • The difference between w+ and r+
    r+: read and write, if the file does not exist, report an error;: w+read and write, if the file does not exist, create

write function

The write() method is used to write the specified string to the file, usage:fileObject.write(str)

read function

fileObject.read():text ——> one whole str
fileObject.readline():one line ——> one str
fileObject.readlines():all line ——> one list with all lines

Pointer and seek function

The pointer will move backward with your read and write operations

  • openAfter the file, the pointer is at the beginning of the file content
  • writeAfter the function, the pointer is after the content written
  • readAfter the function, after the pointer reads the content,
    for example, using read(), the pointer will move from the starting position until the end of the file

Therefore, if you find that you are not getting what you want, it is probably because the position of the pointer is wrong .
This case, should be used seek()to specify the position of the pointer.

Note: seek(0) point to the beginning

2. Simple example

The examples here detail the usage of write, read, readline and readlines.

open function w模式andw+模式

  • First write
# 首次写入
with open('write_files.txt', 'w') as f1:
    f1.write('1 2 3\n4 5 6') # 只要没有退出文件,就可以连续写入
    f1.write('7 8 9')

with open('write_files_w+.txt', 'w+') as f2:
    f2.write('a b c\nd e f')  # 只要没有退出文件,就可以连续写入
    f2.write('g h i')

Result:
(Content written in the file)
Insert picture description here

  • Write again
# 再次写入
with open('write_files.txt', 'w') as f1:
    f1.write('w模式,重新写入...')  # 再次写入会完全清空之前的文件

    # w模式下使用read函数会导致报错(io.UnsupportedOperation: not readable),因为 w 模式不可 读取
    #lines = f1.read()
    #print(lines)

with open('write_files_w+.txt', 'w+') as f2:
    f2.write('w+模式,重新写入...')   # 再次写入会完全清空之前的文件
    f2.seek(0) # 将经过write之后的指针移到文件开头
    red = f2.read()
    f2.seek(0)  # 将经过read之后的指针移到文件开头
    readline = f2.readline()
    f2.seek(0) # 将readline()之后的指针移动到文件开头
    readlines = f2.readlines()
    print(f'read: {red}') # read()读取所有的内容,并且将其作为一个完整的字符串
    print(f'readline: {readline}')  # readline()只读取一行内容,且是字符串格式
    print(f'readlines: {readlines}') # readlines()读取所有行,并将内容放在一个list里(注:由于这里总共只有一行,所以没有用到 for in 来遍历这个列表)

The console prints the result:

read: w+模式,重新写入...
readline: w+模式,重新写入...
readlines: ['w+模式,重新写入...']

What is written in the file:
Insert picture description here

The a mode and a+ mode of the open function

在这里插入代码片
  • a mode
# 1. a 模式
with open('write_file_a.txt', 'a') as f1:
    f1.write('x y z\n1 2 3')
    # w模式下使用read函数会导致报错(io.UnsupportedOperation: not readable),因为 w 模式不可 读取
    # lines = f1.read()
    # print(lines)

result:
Insert picture description here

  • a+ mode
# 2. a+模式
# 首次
with open('write_file_a+.txt', 'a+') as f2:
    f2.write('A B C')
    lines = f2.read()  # 这里是没有东西打印出来的,因为指针现在在最后面
    print(lines)
# 再次
with open('write_file_a+.txt', 'a+') as f2:
    f2.write('1 2 3')
    f2.seek(0) # 将指针移到头部
    lines = f2.read()  
    print(lines)

Print result:

A B C1 2 3

3. json module

import json
data = json.load(open('my_file.json', 'r'))

4. File Operations

(Waiting for perfection)

reference:

  1. Some notes on the open function and the difference between r, r+, w, w+, a, a+
  2. Python file I/O
  3. Detailed explanation of python file opening-the difference between a, a+, r+, w+

Guess you like

Origin blog.csdn.net/Robin_Pi/article/details/114268437