Python---File opening, reading, writing

open file open()

Open an existing file or create a new file

Syntax: open(name, mode, encoding)

name: is a string of the name of the target file to be opened (can include the specific path where the file is located).
mode: Set the mode of opening the file (access mode): r: read-only, w: write, a: append, etc.
encoding: encoding format (UTF-8 is recommended)

example:

f = open('test.txt', 'r', encoding="UTF-8")  # 注意:编码格式需要用关键字作为参数传递
print(type(f))   # <class '_io.TextIOWrapper'>

read file 

read() method: read the length of data

Syntax: file object.read(num) ----- Result: string

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

example:

f = open('test.txt', 'r', encoding="UTF-8") 
print(f"读取10个字节的结果{f.read(5)}")    # 读取内容:我是测试文
print(f"read方法读取全部内容是{f.read()}")  # 注意:这次会接着上一次接着读取
readlines() method: Read all ------ Result: list

Syntax: file object.readlines()

readlines can read the contents of the entire file line by line at once, and returns a list, in which the data of each line is an element.

example:

f = open('test.txt', 'r', encoding="UTF-8")
print(f"read方法读取全部内容是{f.read()}")  # 读取全部
lines= f.readlines()
print(type(lines))  # <class 'list'>
print(lines)        # 空值,原因:第2行已经读取了全部
readline() method: read one line at a time    ----- result: string

Syntax: file object.readlines()

example:

f = open('test.txt', 'r', encoding="UTF-8")
line1 = f.readline()
print(type(line1),line1)    # <class 'str'> 我是测试文件1 (读取一行内容)
for loop reads file lines

example:

# f = open('test.txt', 'r', encoding="UTF-8")
# for line2 in f:
#     print(line2)  # 读取每一行数据

for line3 in open("test.txt","r",encoding="UTF-8"):
    print(line3)   # 读取每一行数据
Close the file close() --- Unoccupy the file

Syntax: file object.close()

with open syntax

Syntax: with open(name,mode,encoding) as filename:

By operating the file in the with open statement block, the close file can be automatically closed after the operation is completed to avoid forgetting the close method.

example:

with open('test.txt', 'r', encoding="UTF-8") as f:
    for line4 in f:
        print(line4)

 File writing write()   

If the file exists, it will be overwritten. If the file does not exist, it will be created.

Syntax: file object.write()   --- open the file through w mode

Notice:

When write is called directly, the content is not actually written to the file, but is accumulated in the program's memory, called a buffer.
When flush is called, the content is actually written to the file.
This is to avoid frequent operations on the hard disk, which leads to inefficiency. Decline (save a bunch and write to disk at once)

File refresh flush()

Syntax: file object.flush()

example:

# f = open("test.txt", "w", encoding="UTF-8")
# f.write("hello")    # 文件写入:内容写入内存中
# f.flush()           # 文件刷新:将内存中积攒的内容,写入到硬盘的文件中
# f.close()           # 关闭文件:内置了flush()功能

f = open("test.txt", "w", encoding="UTF-8")
f.write("你好")  # 会覆盖吧上面写入的内容

File append operation write() 

Syntax: file object.write() --- open the file through a mode

open("test.txt","a",encoding="UTF-8")
f.write("\nhi1")   # 换行输入
f.flush()
f.close()

Small case:

#  小案例
fr = open("test.txt", "r", encoding="UTF-8")
fw = open("test1.txt", "a", encoding="UTF-8")
for i in fr:
    # print(i)
    if i.count("测试") >= 1:
        continue
    else:
        fw.write(i)
print(fw)
fr.close()
fw.close()




# fr = open("test.txt", "r", encoding="UTF-8")
# fw = open("test1.txt", "a", encoding="UTF-8")
# for i in fr:
#     line = i.strip()   # 去除换行符
#     if line.split(",")[4] == "测试":   # 以 , 分割字符串
#         continue
#     else:
#         fw.write(line)
#         fw.write("\n")   # 添加换行符
# fr.close()
# fw.close()

Guess you like

Origin blog.csdn.net/weixin_52053631/article/details/132924640