目录
什么是编码?
为什么使用编码?
1.操作文件需要通过open函数打开文件得到文件对象。
2.文件对象有如下读取方法:

3.文件读取完成后,要使用文件对象.close()方法关闭文件对象,否则文件会被程序一直占用。
通过文件读取操作,读取word.txt文件,统计itheima单词出现的次数。

- # 打开文件
- f = open("word.txt","r",encoding="utf-8")
-
- '''
- 方式1:读取全部内容,通过字符串的count方法统计
- '''
- content = f.read()
- count = content.count("itheima")
- print(f"itheima单词出现的次数是:{count}")
-
- # 关闭文件
- f.close()
- # 打开文件
- f = open("word.txt","r",encoding="utf-8")
-
- '''
- 方式2:一行行读取,一行行统计
- '''
-
- # 计数
- count = 0
-
- # for循环读取文件行
- for line in f:
- word_list = line.strip().split(" ") #strip方法用于去除开头和结尾的空格以及换行符
- # word_list = line.split("\n")[0].split(" ")
- for word in word_list:
- if word == "itheima":
- count += 1
- print(f"itheima单词出现的次数是:{count}")
-
- # 关闭文件
- f.close()
1.写入文件使用open方法的“w”模式进行写入。
2.写入的方法有:
3.注意:
- # 打开文件(如文件不存在则会自动创建)
- f = open("test2.txt","w",encoding="utf-8")
-
- # write方法 将内容写入到内存中
- f.write("hello world!!!")
-
- # flush刷新 将内存中的内容写入到硬盘的文件中
- # f.flush()
-
- # 关闭文件 内置了flush方法
- f.close()
-
- # 打开文件(如文件不存在则会自动创建)
- f = open("test2.txt","w",encoding="utf-8")
-
- # write方法 覆盖前一次写入的内容
- f.write("hello python!!!")
-
- # 关闭文件
- f.close()
test2.txt
![]()
1.追加写入文件使用open方法的“a”模式进行写入。
2.追加写入的方法有(和w模式一致):
3.注意:
- # 打开文件(如文件不存在则会自动创建)
- f = open("test3.txt","a",encoding="utf-8")
-
- # write方法 将内容写入文件
- f.write("hello world!!!")
-
- # 关闭文件
- f.close()
-
- # 打开文件(如文件不存在则会自动创建)
- f = open("test3.txt","a",encoding="utf-8")
-
- # write方法 将内容追加写入文件
- f.write("\nhello python!!!")
-
- # 关闭文件
- f.close()

有一份账单文件,记录了消费收入的具体记录,内容如下:

要求:
- # 打开bill.txt文件
- fr = open("F:/bill.txt","r",encoding="utf-8")
-
- # 打开bill.txt.bak文件
- fw = open("F:/bill.txt.bak","w",encoding="utf-8")
-
- # for循环读取文件行
- for line in fr:
- # strip方法用于去除开头和结尾的空格以及换行符
- line = line.strip()
- if line.split(",")[4] == "正式":
- fw.write(line)
- # 手动写入之前去掉的换行符
- fw.write("\n")
-
- # 关闭文件
- fr.close()
- fw.close()
bill.txt.bak
