3.2.1 文件的读取
1、open()函数
变量名 = open(路径,模式)
打开一个文件,参数1,文件路径,参数2,r/w/a 参数2不写时缺省值为r
filepath = 'D:/note1.txt' # 不能用\,\n是换行符 # 或filepath = r'D:\note1.txt',或filepath = 'D:\\note1.txt' file1 = open(filepath) # 打开一个文件,不写模式时缺省为读取模式 print(file1.read()) # 读取文件内容 file1.close() # 关闭文件 使用open()时,必须要有close(),否则就会一直占用内存
2、with open()用法
# with open用法与open类似,也可以读写文件 # with open不需要写close()方法,自动close # with open可以一次处理多个文件 with open('D:/note1.txt') as file1: print(file1.read())
3.2.2 文件的写入
3.2.3 同时读写文件
编码问题,先换编码。再把字粘贴进去
# 几种读取方法,写一种即可,最好不要两种以上同时用 with open('./123.txt', 'r', encoding='utf-8') as file1: # 相对路径,./是当前目录,../是当前目录的上一层。相对路径比绝对路径的优点在于可以跨平台,mode默认是r,是r可以不写 print(file1.read()) # 读取文件全部内容,返回str型 # 秦时明月汉时关 # 万里长征人未还 # 不加encoding = utf - 8 会报出“gbk codec can't decode byte 0xb3 in position 20的错误”,可以在notepad++中改编码格式,也可以在setting -editor- file encodings-project encoding处改 print(file1.readline()) # 读取文件一行的内容,返回str型 # 秦时明月汉时关 print(file1.readlines()) # 读取文件全部内容,返回list型 # ['秦时明月汉时关\n','万里长征人未还'] print(file1.read().splitlines()) # 读取文件全部内容,返回值是列表,没有\n # ['秦时明月汉时关','万里长征人未还'] print(file1.read().splitlines()[1]) # '万里长征人未还' # 文件的读写,缺省值是r # w+ 可以同时读写,如果文件不存在,则新建,写入时,清空之前的内容写入 # r+ 可以同时读写,如果文件不存在,则报错,写入时,覆盖写入,如文本内容为ABCDEFGHIJKLMN,输入QQ,则覆盖值为QQCDEFGHIJKLMN # a+ 可以同时读写,如果文件不存在,则新建,写入时,追加写入 with open('./123.txt', 'w+') as file1: print(file1.write('你好')) with open('./789.txt', 'r+') as file1: print(file1.write('QQ')) # 文件一开始为abcde,w+写入qq,文件内容保存的是qq # 文件一开始为abcde,r+写入qq,文件内容保存的是qqcde # 文件一开始为abcde,a+写入qq,文件内容保存的是abcdeqq with open('./100.txt', 'w+', encoding='utf-8') as file1: file1.write('莫听穿林打叶声,何妨吟啸且徐行。') # file1.seek(0) # 光标回到文件首位 file1.seek(3) # gbk格式的汉字占2个字节,utf-8格式的汉字占3个字节,如果是seek(1)会报错 print(file1.read()) # 某项目性能测试,要求快速生成多个账号,用户名为sq001-sq999,密码123456,账号和密码之间用逗号隔开 # sq001,123456 # sq002,123456 # sq003,123456 # sq004,123456 # ... # sq999,123456 with open('./账号220408.txt', 'w+') as file1: # 因为文件只打开了一次,所以不是清空写入 for i in range(1, 1000): if i < 999: file1.write(f'sq{i:03},123456\n') # :03格式化字符串,不足三位补齐到三位,不足三位用0补齐 else: file1.write(f'sq{i:03},123456') with open('./aaa/bbb/账号220408.txt', 'w+') as file1: # 因为文件只打开了一次,所以不是清空写入 for i in range(1, 1000): if i < 999: file1.write(f'sq{i:03},123456\n') # :03格式化字符串,不足三位补齐到三位,不足三位用0补齐 else: file1.write(f'sq{i:03},123456')