其实总是笑的人,真的很需要人疼。既然已经伤害了过去,就不要再辜负了将来。
从现在开始,不沉溺幻想,不庸人自扰,踏实工作,好好生活,做一个接近幸福的人。
字节流跟字符没有关系!
1. open函数
Python open() 函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明:
file:必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener:
encoding
encoding:编码,仅 文本模式使用,
1. 写入的时候指定encoding:None 表示缺省编码,依赖操作系统;window 默认的编码是gbk,Linux 默认的编码是 UTF-8;
errors
errors 是一个可选的字符串参数,用于指定如何处理编码和解码错误 - 这不能在二进制模式下使用。
运行输出:解码错误
# 当errors为None或'strict',引发 UnicodeError (或其子类),在 strict_errors() 中实现。
try:
with open('1.txt', encoding='ascii', errors=None) as f:
for line in f:
print(line)
except UnicodeError:
print('解码错误')
运行不会输出:解码错误
# 当errors = 'ignore'时,忽略错误格式的数据并且不加进一步通知就继续执行。在 ignore_errors() 中实现。
try:
with open('1.txt', encoding='ascii', errors='ignore') as f:
for line in f:
print(line)
except UnicodeError:
print('解码错误')
以下错误处理方案仅适用于文本编码。
# 当errors = 'replace'时,使用适当的替换标记进行替换。
# Python 内置编解码器将在解码时使用官方 U+FFFD 替换字符,
# 而在编码时使用 '?'。在 replace_errors() 中实现。
with open('1.txt', mode='w',encoding='ascii', errors='replace') as f:
f.write('我') # 实际文本中写入?(英文问号)
with open('1.txt', mode='r',encoding='ascii', errors='replace') as f:
for line in f:
print(line) # 输出���
# 当errors = 'xmlcharrefreplace'时,使用适当的 XML 字符引用进行替换(仅在编码时)。
# 在 xmlcharrefreplace_errors() 中实现。
with open('1.txt', mode='w',encoding='ascii', errors='xmlcharrefreplace') as f:
f.write('我') #实际文本中写入我
# 当errors = 'backslashreplace'时,使用带反斜杠的转义序列进行替换。
# 在 backslashreplace_errors() 中实现。
with open('1.txt', mode='w',encoding='ascii', errors='backslashreplace') as f:
f.write('我') #实际文本中写入\u6211
with open('1.txt', mode='r',encoding='ascii', errors='backslashreplace') as f:
for line in f:
print(line) # 输出\xe6\x88\x91
# 当errors = 'namereplace'时,使用 \N{...} 转义序列进行替换(仅在编码时)。
# 在 namereplace_errors() 中实现。
with open('1.txt', mode='w',encoding='ascii', errors='namereplace') as f:
f.write('我') #\N{CJK UNIFIED IDEOGRAPH-6211}
newline ——替换换行符
输出写入流 与 流中读取输入
将输出写入流中时:
换行符有多种:
当newline=None,'\n'字符将转换成系统默认行分割符os.linesep
当newline=''或'\n',不进行转换
当newline='\r\n','\n'字符将转换成'\r\n'
当newline='\r','\n'字符将转换成'\r'
with open('1.txt','w',newline='') as f:
f.writelines(['1\r','2\n','3\r\r','4\r\n','5'])
with open('1.txt','rb') as f:
for line in f:
print(line)
-----------------------------------------------------------------
b'1\r2\n' #\n为换行符;
b'3\r\r4\r\n'
b'5'
从流中读取输入时:
当newline=None,'\r','\n','\r\n'被转换成'\n','\n'作为换行符
当newline='',不转换,'\r','\n','\r\n'作为换行符
当newline='\n',不转换,'\n'作为换行符
当newline='\r\n',不转换,'\n'作为换行符
当newline='\r',不转换,'\r'作为换行符
f = open('/test.txt', 'wb+')
f.write(b'python\rwww.python.org\nwww.magedu.com\r\npython3')
f.seek(0)
print(f.read())
print('-'*50)
newlines = [None,'','\n','\r\n']
for nl in newlines:
f = open('/test.txt','r+',newline=nl) # 缺省替换所有换行符
print(f.readlines())
f.close()
-------------------------------------------------------------
b'python\rwww.python.org\nwww.magedu.com\r\npython3'
--------------------------------------------------
['python\n', 'www.python.org\n', 'www.magedu.com\n', 'python3']
['python\r', 'www.python.org\n', 'www.magedu.com\r\n', 'python3']
['python\rwww.python.org\n', 'www.magedu.com\r\n', 'python3']
['python\rwww.python.org\nwww.magedu.com\r\n', 'python3']
with open('1.txt','wb') as f:
f.writelines([b'\x63\r',b'\x64\n',b'\x65\r\r',b'\x66\r\n',b'\x67'])
with open('1.txt',newline='\n') as f:
for line in f:
print(line.replace('\r','\\r').replace('\n','\\n'))
--------------------------------------------------------------------------
c\rd\n
e\r\rf\r\n
g
with open('1.txt','rb') as f:
for line in f:
print(line,end='\n')
---------------------------------------------------------------------------------------------
b'c\rd\n'
b'e\r\rf\r\n'
b'g'
closed
closefd 是 False: 并且给出了文件描述符(文件ID)而不是文件名,那么当文件关闭时,底层文件描述符将保持打开状态。
closefd 必须为 True (默认值):如果给出文件名则 closefd 必须为 True (默认值),否则将引发错误。
可以通过传递可调用的 opener 来使用自定义开启器。然后通过使用参数( file,flags )调用
opener 获得文件对象的基础文件描述符。opener 必须返回一个打开的文件描述符
(使用 os.open as opener 时与传递 None 的效果相同)。
2. read(size=-1)
size表示读取的多少个字符或字节;负数或者None表示读取到EOF
f = open('o:/test4','r+', 0)
f.write("magedu")
f.write('\n')
f.write('马哥教育')
f.seek(0)
f.read(7)
f.close()
# 二进制
f = open('test4','rb+')
f.read(7)
f.read(1)
f.close()
readline 行读取
readline(size=-1)
一行行读取文件内容。size设置一次能读取行内几个字符或字节。
readlines(hint=-1)
读取所有行的列表。指定hint则返回指定的行数。
# 按行迭代
f = open('test') # 返回可迭代对象
for line in f:
print(line)
f.close()
write
write(s),把字符串s写入到文件中并返回字符的个数 writelines(lines),将字符串列表写入文件。
换行符 \n (linux), \r\n (windows) 换行符;
# 操作系统不提供换行符,许多库中会提供换行符;’
f = open('test', 'w+')
lines = ['abc', '123\n', 'magedu'] # 提供换行符
f.writelines(lines)
f.seek(0)
print(f.read())
f.close()
close
flush并关闭文件对象。
其他
| 名称 | 说明 |
|---|---|
| seekable() | 是否可seek |
| readable() | 是否可读 |
| writable() | 是否可写 |
| closed | 是否已经关闭 |













网友评论