文件操作
文件操作
open:Python内置了一个打开文件的函数,open()函数,用来打开一个文件,返回新打开文件的描述符,然后就可以对该打开的文件做任何你想做的操作
语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file:文件名称。
mode:制定了文件打开的方式,函数提供了如下方式,其中,'r'为默认方式。
buffering:如果buffering的值被设置为0,就不会有缓存;如果值为1,访问文件时会缓存行;如果值位大于1的整数,表明了这就是寄存区的缓冲大小;如果取负值,寄存区的缓冲大小则为系统默认。该参数也是非强制性的。
encoding:编码或者解码方式。默认编码方式依赖平台,如果需要特殊设置,可以参考codecs模块,获取编码列表。
errors:可选,并且不能用于二进制模式,指定了编码错误的处理方式,可以通过codecs.Codec获得编码错误字符串
newline:换行控制,参数有:None,'\n','\r','\r\n'。输入时,如果参数为None,那么行结束的标志可以是:'\n','\r','\r\n'任意一个,并且三个控制符都首先会被转化为:'\n',然后才会被调用;如果参数为'',所有的通用的换行结束标志都可以用,但是行结束标识符返回调用不会被编码。输出时,如果参数为None,那么行结束的标志可以是:'\n'被转换为系统默认的分隔符;如果是'','\n'则不会被编码。
closefd:false:文件关闭时,底层文件描述符仍然为打开状态,这是不被允许的,所以,需要设置为ture。
opener:可以通过调用*opener*方式,使用自定义的开启器。底层文件描述符是通过调用*opener*或者*file*, *flags*获得的。*opener*必须返回一个打开的文件描述。将os.open作为*opener*的结果,在功能上,类似于通过None
执行的文件和txt文件同一个目录下,可以不写文件路径,文件读取的时候,行的末尾默认包含回车符号
读取一个文件文件,打印文件内容(txt文件要保存成UTF-8)
r:read 读,为默认模式
w:write 清空写
a:append 在文件的最后面写
"+":表示可同时读写某个文件:
r+ :可读写文件(可读,可写,可追加),写在文件的最开始,会覆盖第一行
w+:写读
a+:追加
r+:read and write 不清空内容,可以同时读和写入内容
w+:write and read 先清空所有文件内容,然后写入,然后你才可以读取你写入的内容
a+:append and read 追加写,所有写的内容都在文件的最后
"b":表示处理二进制文件
rb:read binary
wb:write binary
ab:append binary
"U":表示在读取时,可以将\r \n \r\n自动转换成\n(与r或者r+模式同时使用),因为Windows系统的换行符为\r\n,Linux系统的换行符为\n,加上U则能自动把\r\n转换成\n
rU
r+U
-
with open() 这种方法操作完成后,会自动关闭不需要close()
with open("d:\\python\\a.txt","r",encoding = "utf-8") as fp: print(fp.read())
原理:先执行__enter__方法,执行后执行__exit__方法
class Sample: def __enter__(self): print("In __enter__()") return "Foo" def __exit__(self, type, value, trace): print("In __exit__()") def get_sample(): return Sample() with get_sample() as sample: print("sample:", sample)
-
读取文件 read
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python36\\a.txt","r",encoding = "utf-8") data = fp.read() fp.close() print(data)
-
readline 读取文件中一行内容
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python36\\a.txt","r",encoding = "utf-8") data = fp.readline() fp.close() print(data)
读取文件中的每一行
>>> fp = open("d:\\python36\\a.txt","r") >>> while 1: ... content = fp.readline() ... print(content) ... if content == "": ... break ... hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! >>> fp.close()
-
readlines 把所有的读出来,放到列表中
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python36\\a.txt","r",encoding = "utf-8") #data = fp.readline() data = fp.readlines() fp.close() print(data)
-
读写文件
>>> fp = open("d:\\python36\\a.txt","r+") >>> fp.read() 'test1\ntest2\ntest3\nalex4\nalex5\n\n' >>> fp.tell() 37 >>> fp.write("hello") 5 >>> fp.seek(0.0) 0.0 >>> fp.read() 'test1\ntest2\ntest3\nalex4\nalex5\n\nhello' >>> fp = open("d:\\python36\\a.txt","a+") >>> fp.read() '' >>> fp.tell() 42 >>> fp.seek(0,0) 0 >>> fp.read() 'test1\ntest2\ntest3\nalex4\nalex5\n\nhello' >>> fp.tell() 42 >>> fp.seek(0,0) 0 >>> fp.write("world!") 6 >>> fp.seek(0,0) 0 >>> fp.read() 'test1\ntest2\ntest3\nalex4\nalex5\n\nhelloworld!' >>> fp.close() >>> fp = open("d:\\python36\\a.txt","w+") >>> fp.tell() 0 >>> fp.read() '' >>> fp.write("hello world!") 12 >>> fp.read() '' >>> fp.seek(0,0) 0 >>> fp.read() 'hello world!' >>> fp.close()
读取文件中字符串的个数
>>> with open("d:\\python\\a.txt","r") as f: ... f.read(1) ... 'g' >>> fp = open("d:\\python\\a.txt","r") >>> fp.read(1) 'g' >>> >>> fp.read(1) 'l' >>> fp.read(1) 'o' >>> fp.read(1) 'r' >>> fp.read(1) 'y' >>> fp.read(2) ' r' >>> fp.read(2) 'oa' >>> fp.read(2) 'd ' >>> fp.read(2) 'is' >>> fp.seek(0,0) 0 >>> fp.readline(3) 'glo' >>> fp.readline(3) 'ry ' >>> fp.readline(3) 'roa' >>> fp.readline(5) 'd is ' >>> fp.readline(5) 'great'
计算在文件中,含有“test”的总行数
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("a.txt", "r", encoding="utf-8") data = fp.readlines() fp.close() lines = 0 for i in data: if "test" in i: lines += 1 #print(i) print(lines)
写入文件时需要自己加换行符
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python36\\a.txt","w",encoding = "utf-8") fp.write("test1\n") fp.write("test2\n") fp.close fp = open("d:\\python36\\a.txt","r",encoding = "utf-8") print(fp.read())
生成连续的文件名称内容为空的文件
#!/usr/bin/env python # -*- coding: utf-8 -*- for i in range(1,11): fp = open("d:\\python36\\" + str(i)+".txt","w",encoding = "utf-8") fp.close()
游标跳行
#!/usr/bin/env python # -*- coding: utf-8 -*- with open("d:\\python36\\a.txt","r",encoding = "utf-8") as fp: while(fp.readline()): print(fp.readline())
-
描述符
file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python36\\a.txt","w") print ("文件是否关闭:", fp.closed) print ("文件的访问模式:", fp.mode) print ("文件名称:", fp.name) #关闭文件 fp.close()
-
writelines() 把seq(序列)的内容全部写到文件中(多行一次性写入),也不会自动加入换行符
>>> fp = open("d:\\python\\a.txt","w") >>> fp.writelines(["1\n","2\n","3\n"]) >>> fp.close()
-
flush() 该函数是将缓冲区中的内容写入硬盘,只进行写入文件的操作并不能写入磁盘,需close 或 flush 才会写入磁盘
testList = ['test1\n', 'test2\n', 'test3', '文件操作'] fp = open( "c:\\downloads\\ip2.txt",'w+') print (fp.read(),end="\n") fp.writelines(testList) fp.flush() fp1 = open( "c:\\downloads\\ip2.txt",'r') print (fp1.read(),end="\n") fp.close() fp1.close()
-
fileno() 返回一个长整型的文件标签
>>> fp = open("d:\\python\\a.txt","r") >>> print(fp.fileno()) 3 >>> fp.close()
-
f.tell() 获取当前光标的位置,tell 记录游标的位置 从0 开始
#!/usr/bin/env python # -*- coding: utf-8 -*- with open("d:\\python36\\a.txt","r",encoding = "utf-8") as fp: print(fp.tell()) print(fp.readline()) print(fp.tell())
-
f.seek() 移动光标到指定位置
eg. f.seek(f.tell()) 调整到当前光标所在的位置(字节)
读取几行以后,想从头开始读取
#!/usr/bin/env python # -*- coding: utf-8 -*- with open("d:\\python36\\a.txt","r",encoding = "utf-8") as fp: print(fp.tell()) print(fp.readline()) fp.seek(0,0) print(fp.tell())
seek(offset,whence=0, /)
offset:坐标 正数表示从前向后 负数表示从后向前 0表示最开始的游标
whence:0,1,2
0:表示从文件最开始位置,0,0
1:表示从当前位置开始,基于当前的相对位置,来重置坐标
2:表示从文件的末尾开始,做相对位置,来重置坐标
seek(-5,2) -->末尾向前数5个字符
seek(5,1) 10-->5,现在的坐标是15
注意:1和2使用基于rb模式
#!/usr/bin/env python # -*- coding: utf-8 -*- with open("d:\\python36\\a.txt","r",encoding = "utf-8") as fp: fp.readline() fp.seek(3,0) # 从第三个位置开始读取 print(fp.tell()) print(fp.readline())
-
truncate( [size] ) 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。
如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去
#!/usr/bin/env python # -*- coding: utf-8 -*- with open("d:\\python\\a.txt","r+",encoding = "utf-8") as fp: fp.truncate(10)
-
linecache 该模块允许从任何文件里得到任何的行,并且使用缓存进行优化,常见的情况是从单个文件读取多行
linecache.getlines(filename)从名为 filename 的文件中得到全部内容,输出为列表格式,以文件每行为列表中的一个元素,并以 linenum-1 为元素在列表中的位置存储
linecache.clearcache()
清除缓存
linecache.checkcache(filename)
检查缓存的有效性。如果在缓存中的文件在硬盘上发生了变化,并且你需要更新版本,使用这个函数,执行此函数会讲淘汰的内容删除。如果省略 filename,将检查缓存里的所有条目。不是每次通话都检查。
linecache.updatecache(filename)
更新文件名为 filename 的缓存。如果 filename 文件更新了,使用这个函数可以更新linecache.getlines(filename)返回的列表。如果出错,则返回空列表。
#!/usr/bin/env python # -*- coding: utf-8 -*- import linecache file_content= linecache.getlines('d:\\python\\a.txt') print (file_content) file_content =linecache.getlines('d:\\python\\a.txt')[0:4] print (file_content) file_content =linecache.getline('d:\\python\\a.txt',2) print (file_content) file_content =linecache.updatecache('d:\\python\\a.txt') print (file_content) #更新缓存 linecache.checkcache('d:\\python\\a.txt') #清理缓存,如果你不再需要先前从getline()中得到的行 linecache.clearcache()
删除空行
#!/usr/bin/env python # -*- coding: utf-8 -*- fp = open("d:\\python\\a1.txt","r+") aList = [] for item in fp: if item.strip(): aList.append(item) fp.close() fp = open("d:\\python\\a2.txt",'w') fp.writelines(aList) fp.close()
-
序列化
python持久化的存储数据:
python程序运行中得到了一些字符串,列表,字典等数据,想要长久的保存下来,方便以后使用,而不是简单的放入内存中关机断电就丢失数据。python模块大全中pickle模块就排上用场了, 他可以将对象转换为一种可以传输或存储的格式。
pickle模块将任意一个python对象转换成一系统字节的这个操作过程叫做串行化对象。
python的pickle模块实现了python的所有数据序列和反序列化。基本上功能使用和JSON模块没有太大区别,方法也同样是dumps/dump和loads/load。cPickle是pickle模块的C语言编译版本相对速度更快。
与JSON不同的是pickle不是用于多种语言间的数据传输,它仅作为python对象的持久化或者python程序间进行互相传输对象的方法,因此它支持了python所有的数据类型。
序列化:
#!/usr/bin/env python # -*- coding: utf-8 -*- import pickle as p shoplistfile = 'd:\\shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = open(shoplistfile, 'wb') p.dump(shoplist, f) # dump the object to a file f.close() del shoplist # remove the shoplist # Read back from the storage f = open(shoplistfile,'rb') storedlist = p.load(f) print ('从文件读取的列表对象:',storedlist)
反序列化:
#!/usr/bin/env python # -*- coding: utf-8 -*- import pickle as p shoplistfile = 'e:\\shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] animallist=['hippo','rabbit'] # Write to the file f = open(shoplistfile, 'wb') p.dump(shoplist, f) # dump the object to a file p.dump(animallist,f) f.close() del shoplist # remove the shoplist del animallist # Read back from the storage f = open(shoplistfile,'rb') storedlist = p.load(f) animallist= p.load(f) print (storedlist) print (animallist)

浙公网安备 33010602011771号