学习笔记整理自廖雪峰官网和菜鸟教程
open()
详细用法见:https://www.runoob.com/python/file-methods.html
- 常用语法
open(file,mode=‘r’,encoding=‘utf’)
file:文件地址 - 常用mode:
‘r’ 默认,以只读方式打开文件。文件的指针将会放在文件的开头,不存在文件则报错。
‘w’ 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
‘a’ 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 - 常用对象
file.close() 关闭文件,write写入后close文件再read才有内容
file.read([size])从文件读取指定字节数,无参数或负数读默认所有
file.readline([size])读取整行,包括’\n’字符
file.readlines([sizeint])读取所有行并返回列表,若给定sizeint>0,则是设置一次读多少字节,可减轻读取压力。
file.write(str)在文件中写入str,open w则从删除原有内容,从头开始编辑
file.writelines(sequence)写入字符串列表,换行则需每个字符串加\n
读文件open(path,‘r’)
- 地址转义
#如属性中的地址'C:\Users\Violette\Desktop\data\As I believe.txt'
#需要对斜杠进行转义,以下三种方式都可以
path1='C:\\Users\\Violette\\Desktop\\data\\topen.txt'
path2='C:/Users/Violette/Desktop/data/topen.txt'
path3=r'C:\Users\Violette\Desktop\data\topen.txt'
- 读取文件注意点:
read读取后光标在末尾,再次读取为空,需要f.seek(0)返回起点。
文件读取后close(),避免占用操作系统资源
读写中如果报错则无法close,为了保证无论是否出错都能正确地关闭文件可以try…finally或者with open(最简洁)。
path='C:\\Users\\Violette\\Desktop\\data\\test_read.txt'
f=open(path,'r')#open('路径'、‘模式’、encoding=‘编码’)#r 读取,w 写入
print(f.read())#read对象读入
#read读取后光标在文件末尾,再次read读取后输出为空
print('2nd\n',f.read())
#读取后如果需要再次读取则移动光标到起点
f.seek(0)#将光标移动回起点
print('3rd')
print(f.read())
f.close()#关闭后不能读取,打开后养成关闭习惯。
#output
'''
Still moving under gunfire
Where the weak lies
When no one s beside
2nd
3rd
Still moving under gunfire
Where the weak lies
When no one s beside
'''
保证无论是否出错都能正确地关闭文件:(直接复制廖雪峰的代码)
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
with open('/path/to/file', 'r') as f:
print(f.read())
- 根据需求调用read:
read()读取全部
read(size)每次最多读取size个字节的内容
readline(size)可以每次读取一行内容,如果有size参数则读取size个字符
readlines()一次读取所有内容并按行返回list。
#ANSI编码txt,用gbk
#UTF-8格式txt,用utf8
import os#系统模块
os.chdir('C:/Users/Violette/Desktop/data/')#声明文件目录改变,后面可直接使用目录下文件名
f=open('test_read.txt','r',encoding='utf8')
print(f.read())
f.seek(0)#每次读取完把光标移动回起点
print(f.read(10))#读取10个字符
f.seek(0)
print('1st realine:',f.readline())#按照行读取一行并回车
print('2nd realine:',f.readline())
f.seek(0)
print(f.readline(5))#读取该行的5个字符
f.seek(0)
#readlines常与for结合来遍历文件
print(f.readlines())#返回一个被换行符隔开的列表
f.seek(0)
for line in f.readlines():
print(line)
#st=line.split(':')将line中的内容,用:进行分列
#st[0]st[1]则表示分类后的内容
#st[0].strip()可以去除空格
#output
'''
Still moving under gunfire
Where the weak lies
When no one s beside
Still movi
1st realine: Still moving under gunfire
2nd realine: Where the weak lies
Still
['Still moving under gunfire\n', 'Where the weak lies\n', 'When no one s beside']
Still moving under gunfire
Where the weak lies
When no one s beside
'''
- 二进制文件字符编码
f1=open('heart.png','rb')#打开图像、视频
f1.read()#得到16进制表示的字符
#ANSI编码txt,用gbk
#UTF-8格式txt,用utf8
f2=open('gbk.txt','r',encoding='gbk')
f2.read()
#存在非法编码字符的文件可能报错UnicodeDecodeError,用errors忽略
f = open('errors.txt', 'r', encoding='gbk', errors='ignore')
写文件open(path,‘w’)
- 写入文件注意点:
r没有文件会报错,w没有文件则生成文件,
mode='w’每次open后删除文件内容从头开始输入,追加写入mode=‘a’
write写入内容必须是str,
如果不关闭文件则无法完成写入,此时打开文件中没有内容
writelines(sequence)写入字符串列表不会换行,换行则需每个字符串加\n
#文件写入 open 模式'w'
os.chdir('C:/Users/Violette/Desktop/data/')
#不存在文件则生成
f_write=open('test_write.txt','w',encoding='utf8')
f_write.write('SMG 1307')#写入内容必须是字符串!
#如果不关闭文件则无法完成写入,此时打开文件中没有内容
#writelines换行写入
l=['A','B','C']
f_write.writelines(l)#直接writelines并不会换行,需要加换行\n
for n in range(len(l)):
l[n]=l[n] + '\n'
f_write.writelines(l)#每个元素后都需要加换行\n
f_write.close()
#test_write.txt中的内容
'''
SMG 1307ABCA
B
C
'''’
#追加写入mode='a'
f=open('test_write.txt','a')
f.write('continue')
f.close()
'''
SMG 1307ABCA
B
C
continue
'''
#mode='w'删除原内容
f=open('test_write.txt','w')
f.write('second mode-w')
f.close()
'''
second mode-w
'''