Python3学习之路~2.7 文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
- 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
- 逗弄蜡烛的火苗
- The thousand dreams I dreamed
- 我曾千万次梦见
- The splendid things I planned
- 那些我计划的绚丽蓝图
- I always built to last on weak and shifting sand
- 但我总是将之建筑在易逝的流沙上
- I lived by night and shunned the naked light of day
- 我夜夜笙歌 逃避白昼赤裸的阳光
- And only now I see how the time ran away
- 事到如今我才看清岁月是如何匆匆流逝
- Yesterday when I was young
- 昨日当我年少轻狂
- So many lovely songs were waiting to be sung
- 有那么多甜美的曲儿等我歌唱
- So many wild pleasures lay in store for me
- 有那么多肆意的快乐等我享受
- And so much pain my eyes refused to see
- 还有那么多痛苦 我的双眼却视而不见
- I ran so fast that time and youth at last ran out
- 我飞快地奔走 最终时光与青春消逝殆尽
- I never stopped to think what life was all about
- 我从未停下脚步去思考生命的意义
- And every conversation that I can now recall
- 如今回想起的所有对话
- Concerned itself with me and nothing else at all
- 除了和我相关的 什么都记不得了
- The game of love I played with arrogance and pride
- 我用自负和傲慢玩着爱情的游戏
- And every flame I lit too quickly, quickly died
- 所有我点燃的火焰都熄灭得太快
- The friends I made all somehow seemed to slip away
- 所有我交的朋友似乎都不知不觉地离开了
- And only now I'm left alone to end the play, yeah
- 只剩我一个人在台上来结束这场闹剧
- Oh, yesterday when I was young
- 噢 昨日当我年少轻狂
- So many, many songs were waiting to be sung
- 有那么那么多甜美的曲儿等我歌唱
- So many wild pleasures lay in store for me
- 有那么多肆意的快乐等我享受
- And so much pain my eyes refused to see
- 还有那么多痛苦 我的双眼却视而不见
- There are so many songs in me that won't be sung
- 我有太多歌曲永远不会被唱起
- I feel the bitter taste of tears upon my tongue
- 我尝到了舌尖泪水的苦涩滋味
- The time has come for me to pay for yesterday
- 终于到了付出代价的时间 为了昨日
- When I was young
- 当我年少轻狂
yesterday.txt
基本操作
- f=open("yesterday.txt",encoding='UTF-8') #打开文件句柄
- print(f.read()) #打印全部,读完之后,指针在文件最后,下次读时从文件最后开始读
- for i in range(5):
- print(f.readline()) #打印前5行,读完之后,指针在文件第5行后,下次读时从文件第5行开始读
- print(f.readlines()) #将文件作为一个列表读出来,每一行代表一个元素
- #循环打印所有行,low的写法
- # 吃内存,内存保存全部行,需要将全部行写入内存后再一行行地读,当文件较大时,我们等待时间变长,并且内存也吃不消了
- for line in f.readlines():
- print(line.strip())
- #循环打印除第10行之外的所有行,low的写法
- for index,line in enumerate(f.readlines()):
- if index==9:
- print('-------我是分割线----------')
- continue
- print(line.strip())
- #循环打印所有行,high的写法
- #效率高,文件变成一个迭代器,读一行内存中删一行,内存中只保存一行,牛B了
- for line in f:
- print(line.strip())
- #循环打印除第10行之外的所有行,high的写法
- count=0
- for line in f:
- if count == 9:
- print('-------我是分割线----------')
- count+=1
- continue
- print(line.strip())
- count += 1
- print(f.tell()) #打印指针位置,开始位置0
- print(f.read(5)) #读文件的5个字符
- print(f.tell()) #此时指针位置是5
- print(f.seek(0)) #指针回到位置0
- print(f.readline()) #从头开始打印第一行
- print(f.seekable()) #判断是否可以移动文件的光标位置,如果可以(比如说二进制,字符串文件),返回True,否则返回False
- #并不是所有的文件都是可以把光标移动的,因为Linux是一切皆文件,比如说tty文件就是不可以的
- print(f.encoding) #打印文件的编码格式
- print(f.fileno()) #返回文件句柄在内存中的编号,我们一般不会用到它
- # 操作系统有一个专门的接口,负责调度所有文件。Python读文件不是自己读的,是调用操作系统的IO,
- # 操作系统内部维护了一个类似于现在读了多少文件之类的列表,这就是在其中的编号。
- print(f.name) #打印文件名字
- print(f.isatty()) #判断文件是否是一个终端设备,比如说打印机、Linux上打开的terminal都属于终端设备,
- # 这个是你做一些底层的,比如说和打印机交互等可能会用得到。
- print(f.readable()) #判断文件是否可读
- print(f.writable()) #判断文件是否可写
- print(f.cloed) #判断文件是否已关闭
- f.close() #对文件操作完之后,一定要关闭文件
- #写文件时,是先将内容写入一个缓存中,当缓存满时再一次性将所有内容写入硬盘
- #flush()作用是强制将内容刷新到硬盘
- >>> f=open('test.txt','w')
- >>> f.write('hello1\n') #此时打开test.txt文件,发现文件为空
- 7
- >>> f.flush() #重新打开文件,文件显示一行hello1
- >>> f.write('hello2\n') #重新打开文件,文件未变还是只显示一行hello1
- 7
- >>> f.flush() #重新打开文件,发现hello2已写入文件
- >>> f.close()
f.flush()
- import sys,time
- for i in range(20):
- sys.stdout.write('#')
- sys.stdout.flush() #如果没有这一句,则程序时先将所有的#写到缓存中,再一次性输出
- time.sleep(0.2)
flush()应用场景之进度条
- f=open("yesterday2.txt",'a',encoding='UTF-8') #文件句柄
- f.seek(5)
- f.truncate(10) #截取前10个字符,此时打开文件发现只剩前10个字符
- #此处seek方法没有作用,truncate方法默认就是从文件开头开始截取
- f.close()
f.truncate()
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,读写模式。【可读;可写;可追加】
- #读写模式:可以打开文件读,追加,某些场景会用到
- f=open("yesterday2.txt",'r+',encoding='UTF-8')
- print(f.readline())
- print(f.readline())
- print(f.readline()) #读3行,此时光标在第3行末尾
- print(f.tell())
- f.write("This line shoud be at line3") #你认为新写入的这行应该在第3行末尾,但是实际上这行写在了整个文件末尾
- # Python2.X可以写到第二行开始部分,但是会覆盖文件原来的此处内容
- f.close()
- #读写模式:可以打开文件读,追加,某些场景会用到
- w+,写读模式。
- #写读模式:没什么卵用
- f=open("yesterday2.txt",'w+',encoding='UTF-8') #写读模式,文件存在则清空,没有则创建
- print(f.readline())
- print(f.readline())
- print(f.readline()) #其实一行也读不出来,因为文件清空了
- f.write("---------line 1------------\n")
- f.write("---------line 2------------\n")
- f.write("---------line 3------------\n")
- f.write("---------line 4------------\n")
- print(f.tell())
- f.seek(10)
- print(f.readline())
- f.write("should be at the beginning of the second line")#你认为新写入的这行应该在第2行开始,但是实际上这这行追加到了文件末尾
- #Python2.X可以写到第二行开始部分,但是会覆盖文件原来的此处内容
- f.close()
- #写读模式:没什么卵用
- a+,追加读模式。
- # 追加读模式:a追加模式是不可读的,a+追加读模式默认可读可追加
- f = open("yesterday2.txt", 'a+', encoding='UTF-8')
- print(f.readline()) #不知道为啥没读出来,也没报错?
- f.write("This line shoud be at the end of the file")
- f.close()
- # 追加读模式:a追加模式是不可读的,a+追加读模式默认可读可追加
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- # rb:以二进制格式读文件
- #应用场景:网络传输等
- #Python3.X中网络传输一律用二进制模式,Python2.X中网络传输可以用二进制格式,也可以用字符串格式
- f = open("yesterday2.txt", 'rb')
- print(f.readline())
- print(f.readline())
- print(f.readline())
- f.close()
- # rb:以二进制格式读文件
- wb
- # wb:以二进制格式写文件
- #python2.X中二进制、字符串格式没什么区别,Python3.X中一定要区分开来
- f = open("yesterday2.txt", 'wb')
- #f.write("Hello Binary!") #以字符串格式写会报错
- f.write("Hello Binary!".encode())
- f.close()
- # wb:以二进制格式写文件
- ab
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)。
因为在Windows上换行符是\r\n,在Linux上是\n,U可以统一双方的适配,比如在Linux上打开在Windows上的文件可以用rU。用的比较少,了解即可。
- rU
- r+U
其他语法
- def close(self): # real signature unknown; restored from __doc__
- """
- Close the file.
- A closed file cannot be used for further I/O operations. close() may be
- called more than once without error.
- """
- pass
- def fileno(self, *args, **kwargs): # real signature unknown
- """ Return the underlying file descriptor (an integer). """
- pass
- def isatty(self, *args, **kwargs): # real signature unknown
- """ True if the file is connected to a TTY device. """
- pass
- def read(self, size=-1): # known case of _io.FileIO.read
- """
- 注意,不一定能全读回来
- Read at most size bytes, returned as bytes.
- Only makes one system call, so less data may be returned than requested.
- In non-blocking mode, returns None if no data is available.
- Return an empty bytes object at EOF.
- """
- return ""
- def readable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a read mode. """
- pass
- def readall(self, *args, **kwargs): # real signature unknown
- """
- Read all data from the file, returned as bytes.
- In non-blocking mode, returns as much as is immediately available,
- or None if no data is available. Return an empty bytes object at EOF.
- """
- pass
- def readinto(self): # real signature unknown; restored from __doc__
- """ Same as RawIOBase.readinto(). """
- pass #不要用,没人知道它是干嘛用的
- def seek(self, *args, **kwargs): # real signature unknown
- """
- Move to new file position and return the file position.
- Argument offset is a byte count. Optional argument whence defaults to
- SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
- are SEEK_CUR or 1 (move relative to current position, positive or negative),
- and SEEK_END or 2 (move relative to end of file, usually negative, although
- many platforms allow seeking beyond the end of a file).
- Note that not all file objects are seekable.
- """
- pass
- def seekable(self, *args, **kwargs): # real signature unknown
- """ True if file supports random-access. """
- pass
- def tell(self, *args, **kwargs): # real signature unknown
- """
- Current file position.
- Can raise OSError for non seekable files.
- """
- pass
- def truncate(self, *args, **kwargs): # real signature unknown
- """
- Truncate the file to at most size bytes and return the truncated size.
- Size defaults to the current file position, as returned by tell().
- The current file position is changed to the value of size.
- """
- pass
- def writable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a write mode. """
- pass
- def write(self, *args, **kwargs): # real signature unknown
- """
- Write bytes b to file, return number written.
- Only makes one system call, so not all of the data may be written.
- The number of bytes actually written is returned. In non-blocking mode,
- returns None if the write would block.
- """
- pass
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
- with open('log','r') as f:
- ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
- #python开发规范:一行代码不要超过80个字符,所以打开多个文件时最好分为多行,如下
with open("yesterday.txt",'r',encoding='UTF-8') as f1,\
open("yesterday2.txt", 'w', encoding='UTF-8') as f2:
pass
修改文件
- #VIM修改文件的方式:先把文件读到内存中,在内存中修改,之后再把修改后的文件读出来覆盖原文件
- #另一种修改文件的方式,将文件修改后,写到另一个新文件中,如下
- f=open("yesterday.txt",'r',encoding='UTF-8')
- f_new=open("yesterday.bak",'w',encoding='UTF-8')
- for line in f:
- if "有那么多肆意的快乐等我享受" in line:
- line=line.replace("有那么多肆意的快乐等我享受","有那么多肆意的快乐等Alex享受")
- f_new.write(line)
- f.close()
- f_new.close()
Python3学习之路~2.7 文件操作的更多相关文章
- Python3学习之路~2.8 文件操作实现简单的shell sed替换功能
程序:实现简单的shell sed替换功能 #实现简单的shell sed替换功能,保存为file_sed.py #打开命令行输入python file_sed.py 我 Alex,回车后会把文件中的 ...
- Python3学习之路~2.6 集合操作
集合是一个无序的,不重复的数据组合,它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 常用操作 >>> list1 = ...
- Python3学习之路~2.3 字符串操作
字符串操作 特性:不可修改 name="my \tname is alex" print(name.capitalize()) #首字母变大写 print('Alex LI'.ca ...
- Python3学习之路~2.4 字典操作
字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划.字母来查对应页的详细内容. 定义字典(dictionary) info = { 'stu1101': "Amy ...
- Python3学习之路~0 目录
目录 Python3学习之路~2.1 列表.元组操作 Python3学习之路~2.2 简单的购物车程序 Python3学习之路~2.3 字符串操作 Python3学习之路~2.4 字典操作 Pytho ...
- [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- Python学习系列(五)(文件操作及其字典)
Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件 在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...
- Html5 学习系列(四)文件操作API
原文:Html5 学习系列(四)文件操作API 引言 在之前我们操作本地文件都是使用flash.silverlight或者第三方的activeX插件等技术,由于使用了这些技术后就很难进行跨平台.或者跨 ...
- NO.3:自学python之路------集合、文件操作、函数
引言 本来计划每周完成一篇Python的自学博客,由于上一篇到这一篇遇到了过年.开学等杂事,导致托更到现在.现在又是一个新的学期,春天也越来越近了(冷到感冒).好了,闲话就说这么多.开始本周的自学Py ...
随机推荐
- 6、二、App Components(应用程序组件):1、Intents and Intent Filters(意图和意图过滤器)
1.Intents and Intent Filters(意图和意图过滤器) 1.0.Intents and Intent Filters(意图和意图过滤器) An Intent is a messa ...
- Win10系统安装过程小记
1.网上下载ghost系统http://win10.jysmac.cn/win1064.html 2.使用系统自带的激活工具激活 3.到windows官网下载更新工具更新系统,重新安装https:// ...
- POJ 1661 Help Jimmy(DP/最短路)
Help Jimmy Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 14980 Accepted: 4993 Descripti ...
- eclipse无法连接到makertplace
Eclipse需要安装一个Jcoco的插件,但是连接Eclipse Market的时候,总是出现如下的报错: Cannot open Eclipse Marketplace Cannot instal ...
- javascript基础学习系列-DOM盒子模型常用属性
最近在学习DOM盒子模型,各种属性看着眼花缭乱,下面根据三个系列来分别介绍一下: client系列 clientWidth :width+(padding-left)+(padding-right)— ...
- 洛谷P1042 乒乓球【模拟】
题目背景 国际乒联现在主席沙拉拉自从上任以来就立志于推行一系列改革,以推动乒乓球运动在全球的普及.其中111111分制改革引起了很大的争议,有一部分球员因为无法适应新规则只能选择退役.华华就是其中一位 ...
- tensorflow 添加一个全连接层
对于一个全连接层,tensorflow都为我们封装好了. 使用:tf.layers.dense() tf.layers.dense( inputs, units, activation=None, u ...
- 信1705-2 软工作业最大重复词查询思路: (1)将文章(一个字符串存储)按空格进行拆分(split)后,存储到一个字符串(单词)数组中。 (2)定义一个Map,key是字符串类型,保存单词;value是数字类型,保存该单词出现的次数。 (3)遍历(1)中得到的字符串数组,对于每一个单词,考察Map的key中是否出现过该单词,如果没出现过,map中增加一个元素,key为该单词,value为1(
通过学习学会了文本的访问,了解一点哈希表用途.经过网上查找做成了下面查询文章重复词的JAVA程序. 1 思 思路: (1)将文章(一个字符串存储)按空格进行拆分(split)后,存储到一个字符串(单词 ...
- node 下查看安装插件的最新版本号的方法
例如查看extract-text-webpack-plugin的最新版本号 (不一定时本地安装的插件的版本号) npm view extract-text-webpack-plugin version ...
- CHARACTER SET
mysql> show tables; +-----------------+ | Tables_in_w0811 | +-----------------+ | t | | w_engine ...