SoFunction
Updated on 2024-11-16

An article to help you figure out file manipulation in Python

I. Encoding of documents

There are many codes available in computers:

  • UTF-8
  • GBK
  • Big5
  • et al. (and other authors)

UTF-8It is a globally accepted encoding format

Unless there are special needs, it is always sufficient to encode files in UTF-8 format.

II. Reading of documents

2.1 open() open function

Note: At this point thefbeopenfunction's file object, an object is a special data type in Python that has attributes and methods that can be used with either Object. Properties or Object. Methods to access it, the subsequent object-oriented course will give you a detailed introduction.

name: the name of the target file to be opened (can contain the specific path where the file is located).

mode: set the mode of opening the file (access mode): read-only, write, append, etc.

encoding:encoding format (UTF-8 recommended)

open(name, mode, encoding)

Example:

f = open('./', 'r', encoding='utf-8')

2.2 Three basic access patterns commonly used by mode

paradigm descriptive
f 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.
w Open a file for writing only. If the file already exists open the file and start editing from the beginning, the original content will be deleted . If the file does not exist, create a new file.
a Opens a file for appending. If the file already exists, the new content will be written after the existing content.
If the file does not exist, create a new file for writing.

2.3 Read Operation Related Methods

Operation Summary

manipulate functionality
file object = open(file, mode, encoding) Open the file to get the file object
File object.read(num) Read specified length bytes <br/>read all of the file without specifying num
File object.readline() Read a line
File object.readlines() Read all rows to get the list
for line in file object For looping through the lines of a file, you get one line of data at a time.
File object.close() Close the file object
with open() as f Opening a file via the with open syntax can automatically close the

2.3.1 The read() method:

num indicates the length (in bytes) of the data to be read from the file. If num is not passed, then it means read all the data in the file.

File object.read(num)

2.3.2 The readlines() method

readlinesYou can read the contents of the entire file at once by line, and the return is a list, where each line of data for an element.

f = open('')
content = ()

# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)

# Close the file
()

Example:

readline() method: read one line at a time

f = open('')

content = ()
print(f'first line:{content}')

content = ()
print(f'second line:{content}')

# Close the file
()

The for loop reads the file lines.

for line in open("", "r"):
    print(line)

# each and everylinetemporary variable,It records one line of data from the file

2.3.3 close() Closing a file object

f = open("", "r")

()

# Finally close the file object, i.e., close the occupation of the file, with close.
# If you don't call theclose,At the same time the program does not stop running,Then this file will always bePythonprogram occupancy。

2.3.4 with open Syntax

with open("", "r") as f:
    ()

# By operating on the file in the with open statement block
# Can be turned off automatically after the operation is completedclosefile,Avoid forgetting about it.closemethodologies

Case: Read this file and count the number of occurrences of the word itheima through the file read operation

itheima python itcast
beijing shanghai itheima
shenzhen guangzhou itheima
wuhan hangzhou itheima
zhengzhou bigdata itheima

index = 0
with open('./', 'r', encoding='utf-8') as f:
    for line in f:
        line = ()
        # print(line)
        str = (' ')
        print(str)
        for val in str:
            if val == 'it':
                index += 1

print(f'index:{index}')

III. Writing of documents

Write Operations Quickstart

Attention:

When write is called directly, the content is not actually written to the file, but accumulates in the program's memory, called the buffer.

  • When flush is called, the content is actually written to the file
  • This is done to avoid frequent operation of the hard disk, which leads to a loss of efficiency (save a bunch and write the disk all at once)
  • If the file does not exist, use the "w" mode, a new file will be created.
  • If the file exists, using the "w" mode will clear the original content.

Example.

# 1. Open the file
f = open('', 'w')

# 2. File writing
('hello world')

# 3. Content refresh
()

iv. additions to the documentation

A quick primer on append-write operations

Attention:

  • a mode, file does not exist will create file
  • a mode, the existence of the file will be at the end, append write file

Case Demonstration:

# 1. Open the file, just open it in mode a.
f = open('', 'a')

# 2. File writing
('hello world')

# 3. Content refresh
()

V. Comprehensive case of document operation

Completed file backup case.


name,date,money,type,remarks
Chow Kit Chakra (1977-), * actor,2022-01-01,100000,consumers,formal
Chow Kit Chakra (1977-), * actor,2022-01-02,300000,incomes,formal
Chow Kit Chakra (1977-), * actor,2022-01-03,100000,consumers,beta (software)
Lam Chun Festival,2022-01-01,300000,incomes,formal
Lam Chun Festival,2022-01-02,100000,consumers,beta (software)
Lam Chun Festival,2022-01-03,100000,consumers,formal
Lam Chun Festival,2022-01-04,100000,consumers,beta (software)
Lam Chun Festival,2022-01-05,500000,incomes,formal
Zhang Xueyi (1905-1992), student of the Ming dynasty,2022-01-01,100000,consumers,formal
Zhang Xueyi (1905-1992), student of the Ming dynasty,2022-01-02,500000,incomes,formal
Zhang Xueyi (1905-1992), student of the Ming dynasty,2022-01-03,900000,incomes,beta (software)
Wang Lihong,2022-01-01,500000,consumers,formal
Wang Lihong,2022-01-02,300000,consumers,beta (software)
Wang Lihong,2022-01-03,950000,incomes,formal
Lau Tak-slip (1932-), * politician, President of the * (1993-1998),2022-01-01,300000,consumers,beta (software)
Lau Tak-slip (1932-), * politician, President of the * (1993-1998),2022-01-02,100000,consumers,formal
Lau Tak-slip (1932-), * politician, President of the * (1993-1998),2022-01-03,300000,consumers,formal
f2 = open('', 'a', encoding="utf-8")
with open('bill', 'r', encoding="UTF-8") as f:
    for line in f:
        line = ()
        str = (',')
        if str[4] == 'Testing':
            continue
        else:
            (f'{line}\n')

()

to this article about a paper to take you to understand the file operations in Python article is introduced to this, more related Python file operations content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!