#1读写文本数据:
#1.1.1 对文本数据进行处理,可能需要面对不同的编码格式的文件
#1.1.2 解决方案:
#使用open()函数和rt模式配合读取文本文件:
with open(‘somefile.txt’,mode=‘rt’) as fd:
data = fd.read()#一次性读取文件中的所有内容到程序中;原型:read([size]) size–:读取的字节数
print(data)
‘’’
hello world
hello python
hello everyone
hello everybody
‘’’
with open(‘somefile.txt’,‘rt’) as fd:
for line in fd:#逐行遍历文件对象中的内容
print(line)#打印每行内容
‘’’
hello world
hello python
hello everyone
hello everybody
‘’’
#系统默认的文本编码格式可以通过sys.getdefaultencoding()来查看,这项设定都被设定为utf-8。
#如果已知了某个文件额编码格式,可以通过对open()的参数encoding进行修改来满足编码格式的要求。
#open()中的默认参数errors可以进行修改‘replace’和‘ignore’
#replace:将错误处替换为?
#ignore:忽略错误将错误替换为‘’
#2、将输出重定向到文件中
#2.1 将print()函数输出重定向到某个文件
#2.2 要保证文件以文本写或读写模式打开即可;二进制模式打开会报错!
with open(‘somefile.txt’,‘rt+’) as fd:
print(‘hello world!!!’,file=fd)
with open(‘somefile.txt’,‘rb+’) as fd:
print(‘nimama’,file=fd)
报错如下:
Traceback (most recent call last):
File “F:/file_io/file_IO.py”, line 166, in
print(‘nimama’,file=fd)
TypeError: a bytes-like object is required, not ‘str’
#3、以不同的分隔符或行结尾符完成打印
#修改print()函数中sep和end两个默认参数即可实现
#同样还是有修改分隔符的其他方法: str.join()此方法只能处理字符串
str1 = ‘hello world!’
str2 = ‘,’.join(str1)
print(str2) # h,e,l,l,o, ,w,o,r,l,d,!
str3 = ‘|’.join((‘heo’,‘a’,‘b’))
print(str3) # heo|a|b
str4 = ‘~’.join((1,2,3)) # TypeError: sequence item 0: expected str instance, int found
4、读写二进制数据:
读写二进制文件,如图像,声音等
4.1 解决方案:
使用open()的rb或wb模式就可实现二进制文件的读写
在读中最重要的就是所有的数据都将以Byte string(字节串)形式返回;而不是文本字符串
在写中最重要的就是所有数据是以对象的形式来提供,而且该对象可以将数据以字节形式暴露出来(如字节串或者bytearray对象)
4.2 注意:
字节串在遍历时会返回该字节对应的十进制整数,而非像字符串一样返回该位置的字符
字节串是普通字符串前加b就是字节串
byte_str = b’hell’
for x in byte_str:
print(x)
104
101
108
108
4.3 如果想在二进制文件中读取或写入文本内容,请确保进行编码或者解码操作,如下:
with open(‘somefile.bin’,‘wb’) as fd:
text = ‘hello world!’
fd.write(text.encode(‘utf-8’))
with open(‘somefile.bin’,‘rb’) as fd:
data = fd.read(16)
text = data.decode(‘utf-8’)
print(text)
一个鲜为人知的行为是,像数组和C结构体这样的对象可以直接用来进行写操作,而不必先将其转换为byte对象,实例如下:
import array
nums = array.array(‘i’,[1,2,3,4])
with open(‘somefile.bin’,mode=‘wb’) as f:
f.write(nums)
with open(‘somefile.bin’,mode=‘rb’) as f:
data = f.read()
text = data.decode(‘utf-8’)
print(text,type(text))
实际上,只要是实现了’缓冲区接口‘的对象均可如上操作。有许多对象还支持将二进制数据直接写入到其底层内存中,使用文件描述符的readinto()方法即可
#5、对已经不存在的文件执行写入操作
#想要将数据写入到一个文件中,但只在该文件不在文件系统时才这么做
#5.1 解决方案:
这个问题可以用鲜为人知的x模式替代常见的w模式来解决。x模式只有在文件不存在时才会执行,否则会报异常
这个模式x可以很好的防止w再次写入覆盖原先文件中的内容
with open(‘somefile.bin’,‘wb’) as fd:
text = ‘hello’
fd.write(text.encode(‘utf-8’))
with open(‘somefile.bin’,‘xb’) as fd:
fd.write(‘a’.encode(‘utf-8’))
Traceback (most recent call last):
File “F:/file_io/file_IO.py”, line 231, in
with open(‘somefile.bin’,‘xb’) as fd:
FileExistsError: [Errno 17] File exists: ‘somefile.bin’
#也可以如下进行检测:
import os
if not os.path.exists(‘somefile’):
with open(‘somefile’,‘wt’) as fd:
fd.write(‘hello\n’)
else:
print(‘file exists’)
#6、在字符串上执行IO操作