文件处理
打开windows文件中方式:
# f = open(r'C:UsersfengziDesktopa.txt','a',encoding='utf-8')
# f = open('C:\Users\fengzi\Desktop\a.txt','a',encoding='utf-8')
# f = open('C:/Users/fengzi/Desktop/a.txt','a',encoding='utf-8')
字符编码类型:
utf-8 gbk gb2312 mbcs unicode
需要了解的
# f = open(r'C:UsersfengziDesktopa.txt','a',encoding='utf-8')
# f.flush()#保存
# res = f.readable()#判断文件是否可读
# res = f.writable()#判断文件是否可写
# print(res)
# f.close()
#需要掌握的
#应用程序是不能直接操作硬件的,应用程序需要通过os操作硬件
#用什么字符编码写的,你就需要用什么字符编码读,写。
#读方法
#8位等于1字节,1024bytes(字节)是1kb,
# f = open(r'C:UsersfengziDesktopa.txt','r',encoding='utf-8')
# data = f.read(4)#4是字符不是字节(读取光标右边的4个字符)
# print(data)
# f.close()
# f = open(r'C:UsersfengziDesktopa.txt','r',encoding='utf-8')
# f.read(0)
# data = f.read()#读取光标右边所有字符
# print(data)
# f.close()
# f = open(r'C:UsersfengziDesktopa.txt','r',encoding='utf-8')
# data = f.readline()#readline按行读取
# print(data)
# f.close()
#写方法(覆盖)
# f = open(r'C:UsersfengziDesktopa.txt','w',encoding='utf-8')
# f.write('哈哈哈,哈哈哈')#write方法覆盖原有内容
# f.writelines(('你','好','美','女','11'))#把列表或者元组拼接成一行字符串写入文件中
# f.close()
#写方法(不覆盖)
# f = open(r'C:UsersfengziDesktopa.txt','a',encoding='utf-8')
# f.write('哈哈哈,哈哈哈')
# f.writelines(['s','b'])
# f.close()
bytes类型操作文件
# a = '你好'.encode('utf-8')#转码
# print(a.decode('utf-8'))#解码
# f = open(r'C:UsersfengziDesktopa.txt','rb')
# print(f.read().decode('utf-8'))
# f.close()
# b'你好'不可以转化成bytes,b'abc'可以把abc字符串转化成bytes
# f = open(r'C:UsersfengziDesktopa.txt','wb')
# f.write(b'123')
# f.close()
# with方式打开,不用手动关闭文件
# 0模式可以用在bytes类型和字符类型,1,2模式只能用在bytes类型下
# 常用汉字在utf-8当中占3个字节,生僻字占的更多
# with open(r'C:UsersfengziDesktopa.txt','rb') as f:
# f.seek(0)#把光标移动到开头
# data = f.read()
# print(data)
# f.read(1)
# f.seek(5,1)#1代表相对位置
# print(f.read().decode('utf-8'))
# f.seek(-4,2)#2代表把光标移动到末尾
# data = f.read()
# print(data)