参考资料:b站

文章目录

    • 文件处理与编码转换
      • python文件操作
        • open方法基本使用
        • 读模式:循环读取文件&查找
        • flush seek tell truncate方法
        • 修改文件
        • 处理不同编码的文件
        • 进制模式与编码

文件处理与编码转换

python文件操作

对文件操作有2种,文本文件、二进制文件(视频、图片等)

open方法基本使用

# open 方法基本使用
open(file,mode='r',encoding=None)
# 几种打开模式
默认是rt模式

# 文件打开之后的方法:


# 本地测试
PS C:\Users\taohy> cd C:\Users\taohy\Desktop
PS C:\Users\taohy\Desktop> python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> open('test.txt')
<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp936'>

# 打开文件
>>> open('test.txt')
<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp936'>
# 创建文件
>>> open('test.txt','w')
<_io.TextIOWrapper name='test.txt' mode='w' encoding='cp936'>
# 每次open游标都会跟着走到最后,再read往后就没有内容了
>>> f = open('test.txt')
>>> f.read()
'111'
>>> f.read()
# 创建文件 写入内容到文件再查看 写入之前会把之前的内容清空
>>> f= open('test.txt','w')
>>> f.read() # 写模式下读是不允许的,会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>> f.write('my name is taohy')
16
>>> f.write('age is 18')
9
>>> f.write('job is developer')
16
>>> f.close() # 关键
# 查看文件,是不会换行的,需要自己执行换行

# 创建文件 写入内容到文件再查看
>>> f= open('test.txt','w')
>>> f.write('taohy\n')
6
>>> f.write('18\n')
3
>>> f.write('developer\n')
10
>>> f.close() #关键

# 用x创建文件,如果已存在,就报错
>>> f=open('test.txt','x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'test.txt'
>>>
# 提示 在命令行窗口如何查询模块的方法
>>> import random
>>> help(random) # 可以看到官网说明和模块使用说明
Help on module random:

NAME
    random - Random variable generators.

MODULE REFERENCE
    https://docs.python.org/3.10/library/random.html

读模式:循环读取文件&查找

# read特定长度的字符,给1代表一个字符
>>> f =open('test.txt','w')
>>> f.write('陶taohy')
6
>>> f.close()
>>> f= open('test.txt')
>>> f.read(1)
'陶'
>>> f.read(2)
'ta'
>>> f.read(5)
'ohy'
>>>
# 每行读取 
>>> f = open('test.txt')
>>> f.readline()
'name     age       job\n'
>>> f.readline()
'taohy     18       developer\n'
# 判断字符是否在行中
>>> for line in f:
...     if('dabao' in line):
...             print(line)
...
dabao      8       student
# 移动光标
>>> f.seek(0) # 移动到开始位置
0
>>> f.readline()
'name     age       job\n'
# 追加模式 一般用于写日志 a
>>> f = open('test.txt','a')
>>> f.write('wangxy    34    sales\n')
22
>>> f.write('xiaoyang    56    teachers\n')
27
>>> f.close()
>>> f = open('test.txt')
>>> for line in f:
...     print(line)
...
name     age       job

taohy     18       developer

dabao      8       studentwangxy    34    sales

xiaoyang    56    teachers

flush seek tell truncate方法

# 注意:
# 追加模式下,即使通过f.seek()把光标移动到其他位置,再write()的时候,依然写道最后的。
# 但是,f.seek(10),然后再f.truncate(),会生效,实现文件截断至保留10个字符。
# flush 方法 调用之后直接写入内存
>>> f = open('test.txt','w')
>>> f.write('test11      5      test11\n')
26
>>> f.flush()
>>> f.write('test22      6     test22\n')
25
>>> f.flush()

# seek方法 光标定位
# tell方法 获取光标位置
>>> f.seek(5)
5
>>> f.tell()
5
>>> f.seek(20)
20
>>> f.tell()
20
# truncate方法 截断文件,保留光标前内容
>>> f.tell()
20
>>> f.truncate()
20
>>>

修改文件

# r+ 模式可以修改文件
# 直接调用f.write(),会从头开始写,然后往后覆盖。。。如果只覆盖了某个文字的一半,就是乱码
>>> f = open('test.txt','r+')
>>> f.readline()
'test11 '
>>> f.write('test22')
6
>>> f.flush()
>>> f.seek(0)
0
>>> f.readline()
'test11 test22'

# 替换特定字符 seek移动的是字节 tell返回的也是字节数
# 先要找到位置tell报错,在循环中不能使用——错误思路
# 先把文件加载到内存,替换要改的部分,清空文件内容,把新内容写上去
>>> f= open('test22.txt','r+',encoding='UTF-8')
>>> content = f.read()
>>> content
'今天高兴test22'
>>> content = content.replace('高','happy')
>>> print(content)
今天happy兴test22

>>> f.truncate(0)
0
>>> f.tell()
18
>>> f.seek(0)
0
>>> f.read()
''
>>> f.write(content)
14
>>> f.tell()
20
>>> f.seek(0)
0
>>> f.read()
'今天happy兴test22'

# 删除文件
import os
os.remove('test.txt.bak')

处理不同编码的文件

# encoding 参数传值
>>> f= open('gbk.txt',encoding='UTF-8')
>>> f.read()
'gbk 您好!'
>>> f= open('gbk.txt',encoding='gbk')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0x81 in position 12: incomplete multibyte sequence
>>>
# vscode中,查看对象的方法或属性,鼠标移动到对应的方法,按住ctrl键,跳转即可查看。


进制模式与编码

# 打开 jpg二进制图片
>>> f = open('taohy.jpg')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
>>> f = open('taohy.jpg','rb')
>>> f.read() # b开头的二进制文件
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\....
# 字节类型
# wb 二进制模式写 报错
>>> f= open('2进制写文件.txt','wb')
>>> f.write('你好')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
# 对应的内容unicode 要转换成utf-8模式
>>> s = '你好'
>>> f.write(s.encode('utf-8')) 
# 编码后变成字节类型
# 编码
>>> s = '陶' # unicode 
>>> s_utf8 = s.encode('utf-8') # utf-8 编码
>>> print(s_utf8)
b'\xe9\x99\xb6'  # utf-8 中文字符3个字节
>>> s_gbk = s.encode('gbk')  # gbk 编码
>>> print(s_gbk)  # gbk 中文字符2个字节
b'\xcc\xd5'

# 解码
>>> print('utf-8解码',s_utf8.decode('utf-8')) # utf-8解码>>> print('gbk解码',s_gbk.decode('gbk'))    # gbk解码>>>

# utf-8写二进制文件
>>> f = open('2进制写utf8文件','wb')
>>> s = '你好'.encode('utf-8')
>>> f.write(s)
6
>>> f.close()
>>> f=open('2进制写utf8文件','rb')
>>> data = f.read()
>>> print(data)
b'\xe4\xbd\xa0\xe5\xa5\xbd'

# gbk写二进制文件
>>> f = open('2进制写gbk文件','wb')
>>> s = '你好'.encode('gbk')
>>> f.write(s)
4
>>> f.close()
>>>
>>> f = open('2进制写gbk文件','rb')
>>> data = f.read()
>>> print(data)
b'\xc4\xe3\xba\xc3'

更多推荐

基础自学Python编程7天快速入门 Day5