python文件管理

文件管理:无法直接操作硬盘上的文件,需要通过给系统下达命令来实现对硬盘上文件的管理。

gbk:两个字节对应一个字符

utf-8:3个字节对应一个字符

1. 读 r/rb

第一种方法:

1. 给操作系统发送一个打开文件的信号

f=open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk')

f=open('C:\\Users\\15116\\Desktop\\test.txt','r',encoding='gbk')

f=open('C:/Users/15116/Desktop/test.txt','r',encoding='gbk')

2. 将读取到的内容保存在内存中

f.read()

3. 将打开的文件关闭,这种方式打开的文件必须关闭,否则会一直占用系统资源。

f.close()

第二种方法:此方法打开文件不用手动关闭,with有关闭的作用。

with open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk') as f:

f.read() #空一个TAB的距离

print(f.read()) # 打印读到的内容

实例1:读文件的所有内容

with open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk') as f:

a=f.read()

 

with open(r'C:\Users\15116\Desktop\test.txt','rb') as f:

a=f.read()

print(a)

clip_image003

实例2:按照几个字符读

with open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk') as f:

a=f.read(3) # 读出3个字符

print(a)

必须掌

实例3:按照行来读

with open(r'C:\Users\15116\Desktop\test.txt','r') as f:

a=f.readline()

实例4:把内容转化成列表的形式

with open(r'C:\Users\15116\Desktop\test.txt','r') as f:

a = f.readlines()

print(a)

clip_image004

2. 写

w/wb是覆盖编辑

实例1:

with open(r'C:\Users\15116\Desktop\test1.txt','wb')as f:

f.write('测试'.encode('gbk')) #如果不是中文,是字母或者别的,可以在添加的内容前加一个b即可完成转译。

测试

with open(r'C:\Users\15116\Desktop\test1.txt','w')as f:

f.write('测试2')

测试2

a/ab是追加编辑

with open(r'C:\Users\15116\Desktop\test1.txt','a')as f:

f.write('哈哈')

with open(r'C:\Users\15116\Desktop\test1.txt','ab')as f:

f.write('嘻嘻'.encode('gbk'))

将列表中的元素添加到文档中

with open(r'C:\Users\15116\Desktop\test1.txt','a')as f:

f.writelines(['a','b','c','d'])

3. 检测该文档可读还是可写,返回布尔形式的结果

res = f.readable()#是否可读

res = f.writable()#是否可写

print(res)

4. 光标的移动

seek中光标的移动模式 0:顶头 1:相对位置 2:末尾位置,其中1和2只能在bytes模式下去运行(0,1) (0,2)除外。

f.seek(3,0) #3代表移动几个字节,0代表光标的移动模式。

读取的内容是广播开始的位置到结尾的位置之间的内容。

utf8中一个汉字3个字节,生僻字占的更多;gbk中一个字符对应两个字节

实例1:

with open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk') as f:

a=f.read(2)

res=f.read(1)

print(res) #此时读出的是第三个字符的内容

实例2:seek(2,0)0可以在gbk或者utf-8模式下使用

with open(r'C:\Users\15116\Desktop\test.txt','r',encoding='gbk') as f:

f.read(2)

f.seek(2,0)

c=f.read(1)

print(c)

打印出来的是行首的第二个字符的内容

实例3:

with open(r'C:\Users\15116\Desktop\test.txt','rb') as f:

f.read(2) # 代表2个字节

f.seek(2,1) #字节

c=f.read(2) # 字节

print(c.decode('gbk'))

因为此时是以bytes模式下读取的,因此,此时的read都是读的字节,

实例4:2是从末尾位置开始,从-1开始计数

with open(r'C:\Users\15116\Desktop\test.txt','rb') as f:

f.seek(-4,2) #从末尾位置开始往前移动4个字符的位置

a=f.read()

print(a.decode('gbk'))

posted @ 2019-05-03 19:30  lbzzs  阅读(246)  评论(0编辑  收藏  举报