Python文件操作

1. 文件的编码


文件的主要操作:打开 -- 读写 -- 关闭

 

 

2. 文件的读取


mode"r", "w", "a", 分别指读,写,追加!

练习:

# 方式一
with open("./word.txt", "r", encoding="UTF-8") as f:
    count = 0
    for line in f:
        count += line.strip("\n").split(" ").count("itheima")
        # count += line.replace("\n", "").split(" ").count("itheima")
    print(count)

# 方式二
with open("./word.txt", "r", encoding="UTF-8") as f:
    print(f.read().count("itheima"))

 

 

3. 文件的写入


 

 

4. 文件的追加


 

 

5. 文件操作的综合案例


f1 = open("C:/Users/12192/Desktop/bill.txt", "r", encoding="UTF-8")
f2 = open("C:/Users/12192/Desktop/bill.txt.bak", "w", encoding="UTF-8")
for line in f1:
    line = line.strip()  # 把字符串前后的换行符、空格等删除
    if line.split(",")[-1] == "测试":
        continue
    else:
        f2.write(line)
        f2.write("\n")  # 由于前面对内容进行了strip()操作,所以要手动写出换行符
f1.close()
f2.close()

  

posted @ 2023-07-29 16:10  Peg_Wu  阅读(3)  评论(0编辑  收藏  举报