翼度科技»论坛 编程开发 python 查看内容

python笔记:第十二章文件

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
1.打开文件

位于自动导入的模块IO中,无需手动导入。
  1. f = open('D:\M\test.txt')
复制代码
若文件不存在,则报错
  1. Traceback (most recent call last):
  2.   File "d:\M\github\Python\Demo\t14.py", line 1, in <module>
  3.     f = open('D:\M\test.txt')
  4.         ^^^^^^^^^^^^^^^^^^^^^
  5. OSError: [Errno 22] Invalid argument: 'D:\\M\test.txt'
复制代码
1.1 文件模式

只指定文件名的话,会得到一个可读文件对象。若想写入文件,必须通过添加参数来指出。
  1. 'r'        以只读方式打开文件。文件的指针将会放在文件的开头,这是默认模式。
  2. 'w'        以写入方式打开文件。如果文件存在则覆盖,如果文件不存在则创建一个新文件。
  3. 'a'        以追加模式打开文件。如果文件存在,则在文件末尾追加写入,如果文件不存在则创建一个新文件。
  4. 'x'        以独占方式创建文件,如果文件已经存在则返回 FileExistsError 错误。
  5. 'b'        以二进制模式打开文件。
  6. 't'        以文本模式打开文件(默认模式)。
  7. '+'        可读写模式(可与其他模式组合使用)。
复制代码

  • 默认模式为rt,将把文件视为Unicode文本,自动执行解码和编码,且默认使用UTF-8编码。
  • 可以使用关键字参数encoding和errors。
  • 若文件为声音图片视频之类的,可以使用二进制模式来禁用与文本相关的功能。、
2.文件的基本方法

2.1 读取和写入

f.write
  1. f = open('test.txt', 'w')
  2. f.write('Hello')
  3. f.close  # 记得关闭
复制代码
  1. f = open('test.txt', 'r')
  2. str1 = f.read(4)  # 读取前4个字符 指针到达第5个字符
  3. print(str1)
  4. str1 = f.read() # 从第五个字符开始读取
  5. print(str1)
  6. >
  7. Hell
  8. o
复制代码
若想让指针回到起始位置,用f.seek(0)
  1. f = open('test.txt', 'r')
  2. str1 = f.read(4)
  3. print(str1)
  4. f.seek(0)  # 指针回溯
  5. str1 = f.read()
  6. print(str1)
  7. >
  8. Hell
  9. Hello
复制代码
2.2 成行地读取和写入

2.2.1 读取方法readline

可以不提供参数,读取一行后返回
test.txt 文件内容为

注意:文件中每一行都有一个换行符,读取时,换行符也会被读取
  1. f = open('test.txt', 'r')
  2. str1 = f.readline()
  3. str2 = f.readline()
  4. print(str1)
  5. print(str2)
复制代码
运行结果
  1. Hello
  2. Bob
复制代码
想要不读取换行符,可用strip()
  1. f = open('test.txt', 'r')
  2. str1 = f.readline().strip()
  3. str2 = f.readline().strip()
  4. print(str1)
  5. print(str2)
复制代码
运行结果
  1. Hello
  2. Bob
复制代码
可以指定读取字符数量
  1. f = open('test.txt', 'r')
  2. str1 = f.readline(5)
  3. print(str1)
  4. > Hello
复制代码
读取文件所有行,以列表返回 readlines
  1. f = open('test.txt', 'r')
  2. str1 = f.readlines()
  3. print(str1)
  4. > ['Hello\n', 'Bob\n', 'bye']
复制代码
默认状态下,VSCode不会即时保存,需要先将test.txt保存,再运行程序
2.2.2 写入方法 writeline

先擦除所有内容,然后再写入
运行前,test.txt文件内容
  1. f = open('test.txt', 'w')
  2. f.writelines('good')
  3. f.close
复制代码
运行后

写入时,不会自动添加换行符,需要自己添加,没有writeline方法,可以使用write
  1. f = open('test.txt', 'w')
  2. f.write('middle')
  3. f.writelines('bad\n')
  4. f.writelines('good')
  5. f.close
复制代码
运行结果

2.3 记得关闭文件!

可以使用 try/finally 语句,再finally中调用close
  1. try:
  2.     f = open('test.txt', 'w')
  3.     f.write('middle')
  4.     f.writelines('bad\n')
  5.     f.writelines('good')
  6. finally:
  7.     f.close
复制代码
还可以使用with语句关闭
  1. # 将文件对象赋给test
  2. with open('test.txt', 'w') as test:  
  3.     test.write('middle')
复制代码
运行后文件自动关闭
3.迭代文件内容

3.1 每次一个字符
  1. with open('test.txt', 'r') as f:
  2.     while True:
  3.         char = f.read(1)
  4.         if not char: break
  5.         print(char, end=' ')
复制代码
文件内容:

运行结果
  1. C h i n a
复制代码
3.2 每次一行

文件内容
  1. with open('test.txt', 'r') as f:
  2.     while True:
  3.         str = f.readline().strip() # 去掉换行符
  4.         if not str: break
  5.         print(str, end=' ')
  6. > China is the best
复制代码
3.3 读取所有内容
  1. with open('test.txt', 'r') as f:
  2.     str = f.read()
  3.     print(str, end=' ')
复制代码
运行结果
  1. China
  2. is
  3. the
  4. best
复制代码
3.4 延迟行迭代fileinput

fileinput 可以轻松地处理多个输入流,包括文件、标准输入流等,同时还支持行迭代和缓冲流处理。还可以对大型文件(几个TB)进行处理。
常见的使用方式包括:

  • 逐行读取文件中的数据,例如上面提到的例子。
  • 处理多个文件,例如通过 glob 模块来指定需要处理的文件列表。
  • 实现管道功能,例如通过 subprocess 模块来实现将命令的输出作为输入流来处理。
文件内容
  1. # 逐行读取文件并统计出现次数
  2. for line in fileinput.input('test.txt'):
  3.     key = line.strip()
  4.     counts[key] = counts.get(key, 0) + 1
  5. # 输出统计结果
  6. for key, value in counts.items():
  7.     print(key, '--', value)
复制代码
运行结果
  1. 1 -- 3
  2. 2 -- 2
  3. 3 -- 1
  4. 4 -- 1
复制代码
来源:https://www.cnblogs.com/lmc7/p/17570092.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具