Python file reading and writing: open + read + close

# -*- coding:utf8 -*-
"""
# editor: hjjdreamer
# create-time: 2022/12/12-22:44
# Python-Script: chapter8-writefile.py
# describe:

"""

# lesson1: open
"""
r == 只读 文件指针在文件的开头 默认模式
w == 只写 从开头编辑,会发生覆盖
a == 追加 已有文件不执行覆盖
"""
# 打开文件
f = open("./data/test.txt", "r", encoding="utf-8")
print(type(f))          # <class '_io.TextIOWrapper'>

# read()
"""
read(num) == 读取数据的长度,没有num,默认是全部
readlines() == 按照行进行一次性读取,返回一个列表,每一行数据为一个元素
"""
# print(f"read 10 字节 == {f.read(10)}")
# print(f"read all == {f.read()}")

print("\n--------------------------------\n")

# lines = f.readlines()
# print(f"lines 对象类型: {type(lines)}")     # <class 'list'>
# print(f"lines context == {lines}")
# lines context == ['20221212-test-open\n', 'afsdf123fa\n', 'asfasdfasf\n', '123424sgsdgf\n', 'asfasf42352\n', 'daf3542524fa']

# readline()
"""
一次读取一行内容
"""
# line1 = f.readline()
# line2 = f.readline()
# line3 = f.readline()
# print(f"line1 = {line1}")       # line1 = 20221212-test-open
# print(f"line2 = {line2}")       # line2 = afsdf123fa
# print(f"line3 = {line3}")       # line3 = asfasdfasf

# for 循环
for line in f:
    print(f"每一行数据是: {line}")


# 关闭 close() == 停止文件占用
f.close()

# with open
"""
操作完成后,自动关闭文件,避免忘掉close的方法
"""
with open("./data/test.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line)


# lesson2: example
with open("./data/words.txt", "r", encoding="utf-8") as f:
    content = f.read()
    count_ith = content.count("itheima")
    print(f"itheima count == {count_ith}")

f = open("./data/words.txt", "r", encoding="utf-8")
count1 = 0
for line in f:
    line = line.strip()        # 去除开头结尾的空格和换行符
    # 第1次debug == print
    print(line)
    words = line.split(" ")
    # 第2次debug == print
    # print(words)
    for word in words:
        if word == "itheima":
            count1 += 1
print(f"itheima count1 == {count1}")
f.close()

# lesson3: write + flush
"""
write == 内存执行 + flush == 写入文件
"""
f = open("./data/test-write.txt", "w", encoding="utf-8")
# write == 内存
f.write("20221212-write-test")

# flush == 硬盘
f.flush()
# time.sleep(600)
f.close()       # 内置 flush 功能


# append
f = open("./data/test-append.txt", "a", encoding="utf-8")

# write something
f.write("20221212-test-append-init")
f.flush()
f.write("\npython study-asdfsfa")     # 后面直接追加
f.close()



# 案例
# 读取文件
fr = open("./data/bill.txt", "r", encoding="utf-8")
# 创建文件,准备写入
fw = open("./data/bill.bak", "w", encoding="utf-8")
# 循环读取文件
for line in fr:
    # 判断内容执行操作
    line = line.strip()    # 前后去除空格 + 回车 + 换行符
    if line.split(",")[4] == "测试":
        continue
    # 内容写出
    fw.write(line)
    # 前期处理了换行符,现在要进行补充
    fw.write("\n")

# close
fw.close()
fr.close()

Guess you like

Origin blog.csdn.net/m0_59267075/article/details/128295997