前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【13】Python之常用文件操作

【13】Python之常用文件操作

作者头像
py3study
发布2020-01-06 16:33:21
3600
发布2020-01-06 16:33:21
举报
文章被收录于专栏:python3python3

File对象使用open函数来创建,下表列出file对象常用的函数。

序号

方法

描述

1

file.close()

关闭文件。关闭文件后不能在进行读写。注:文件打开后别忘记关闭。

2

file.flush()

刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件,而不是被动的等待缓冲区的写入。(缓冲区好比PC机的内存)

3

file.fileno()

返回一个整型的文件描述(file descriptor FD整型),可以用在如OS模块的read方法等一些底层操作上

4

file.isatty()

如果文件连接到一个终端上返回True,否则False

5

file.next()

返回文件下一行

6

file.read([size])

从文件读取指定的字节数,如果未给定或为负则读取所有。

7

file.readline([size])

读取整行,包括\n字符

8

file.readlines([sizeint])

读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行,实际读取值肯能比sizeint较大,因为需要填充缓冲区

9

file.seek(offset[, whence])

设置文件当前位置

10

file.tell()

返回文件当前位置

11

file.truncate([size])

从文件的首行首字符开始截断,截断文件为size个字符,五size表示从当前位置截断;截断之后V后面的所有字符被删除,其中Windows系统下的换行代表2个字符大小。

12

file.write(str)

将字符串写入文件,没有返回值。

13

file.writelines(sequence)

向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

file.close()

概述:关闭文件。关闭文件后不能在进行读写。注:文件打开后别忘记关闭。

f=open('so_file',encoding="utf-8")  #打开文件,并读取。Windows上默认字符集GDK,所以这里指定了字符集,不然会报错。(#UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 106: illegal multibyte sequence ) data=f.read()  #将读取的内容赋值给data print(data) f.close()  #一定要关闭,才是一个完成的读取文件方式。

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读; 不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab File.flush() 概述:用来刷新缓冲区的,即将缓冲区的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。 一般情况下文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新她,这时就可以使用flush方法。

f=open('so_file','wb')  #打开文件,并读取。 # data=f.read()  #将读取的内容赋值给data # print(data) print("file name is :",f.name) f2=f.flush() # print(f2) f.close()

运行结果:

file name is : so_file

注意:二进制模式下,不支持编码参数

缓冲flush作用效果图:(执行有惊喜)

import sys,time f=open('so_file','r+',encoding="utf-8") for i in range(20):     sys.stdout.write("#")     sys.stdout.flush()     time.sleep(0.1)

运行结果:

####################

File.fileno()

概述:返回一个整型的文件描述(file descriptor FD整型),可以用在如OS模块的read方法等一些底层操作上

f=open('so_file','wb')  #打开文件,并读取。 # data=f.read()  #将读取的内容赋值给data # print(data) print("file name is :",f.name) # f2=f.flush() fidd=f.fileno() print("file》》》",fidd)  #返回文件描述符 f.close()

运行结果:

file name is : so_file

file》》》 3

File.isatty()

概述:如果文件连接到一个终端上返回True,否则False

f=open('so_file','wb')  #打开文件,并读取。 # data=f.read()  #将读取的内容赋值给data # print(data) print("file name is :",f.name) fin=f.isatty() print("file》》》",fin) f.close()

运行结果:

file name is : so_file

file》》》 False

File.readline()

概述:读取整行,包括\n字符

f=open('so_file','r+',encoding="utf-8") print("file name is :",f.name) # for index in range(5): #     line = next(fo) #     print ("第 %d 行 - %s" % (index, line)) data=f.readline() #不填默认读取一行 print("读取首行:",data) data1=f.readline(5)  #读取N个字符 print("读取%s个字符" %(data1),data1) f.close()

运行结果:

file name is : so_file

读取首行: Somehow, it seems the love I knew was always the most destructive kind

读取Yeste个字符 Yeste

File.readlines()

概述:用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。 如果碰到结束符 EOF 则返回空字符串。

f=open('so_file','r+',encoding="utf-8") print("file name is :",f.name) data=f.readlines()  #全部打印结尾加\n print(data) f.close()

第十行不打印

f=open('so_file','r+',encoding="utf-8") for index,info in enumerate(f.readlines()): if index==9: print('--------GO-------') continue print(info.strip()) f.close()

高效的循环方法:

f=open('so_file','r+',encoding="utf-8") count=0 for line in f: if count==9: print('---------GO--------')         count +=1 continue print(line)     count +=1

File.tell()

概述:反馈文件当前位置,即文件指针当前位置

f=open('so_file','r+',encoding="utf-8") data=f.readline() print("读取数据为:%s"%(data)) data2=f.tell() print("当前位置:%s" %(data2))

运行结果:

读取数据为:Somehow, it seems the love I knew was always the most destructive kind

当前位置:72  #read结束,全文72行

File.seek()

概述:指针移动到之指定位置

File.truncate()

概述:用于从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后 V 后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。

.truncate()什么都不写,清空文件。指定数字就会截断个数。

File.write()

修改部分值,写入新文件。

f=open('so_file','r',encoding="utf-8") f_new=open('so_file2','w',encoding="utf-8") for line in f: if "生命的滋味是甜的" in line:         line=line.replace("生命的滋味是甜的","生命的滋味是幸福的")     f_new.write(line) f.close() f_new.close()

运行结果:

So_file文件内容

Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue 就如舌尖上的雨露 I teased at life as if it were a foolish game 我戏弄生命 视其为愚蠢的游戏 The way the evening breeze 就如夜晚的微风 May tease the candle flame

So_file2文件内容(新文件)

Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是幸福的 As rain upon my tongue 就如舌尖上的雨露 I teased at life as if it were a foolish game 我戏弄生命 视其为愚蠢的游戏 The way the evening breeze 就如夜晚的微风 May tease the candle flame

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档