文件操作
文件操作流程
1、打开文件,得到文件句柄并赋值给一个变量
2、通过句柄对文件进行操作
3、关闭文件
现有文件如下:
-
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
当我年少轻狂
基本操作:
f = open('lyrics', encoding='utf-8') # 打开文件,python3.x中必须要指定encoding参数
first_line = f.readline()
print('first line:', first_line) # 读一行
print('我是分隔线'.center(50, '-'))
data = f.read() # 读取剩下的所以内容,文件大时不要用
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
data = open("yesterday",encoding='utf-8') # 这种模式后续是无法再对文件进行操作
f = open("yesterday",encoding='utf-8') # 文件句柄。这样就可以对文件进行更多的操作.读写操作未设置!
f = open("yesterday2",'a',encoding='utf-8') # r是读取文件,w是创建文件,a追加模式;
data = f.read() # 读取文件
data2 = f.read() # 再次读取同一文件
print(data)
print('-------data2------',data2) # 文件读取的指针已经移动到了文件的最后,所以data2是空的。
f.write("\n我爱北京天安门,\n")
f.write("天安门上太阳升。")
f = open("yesterday",'r',encoding='utf-8')
for i in range(5):
data = f.readline()
print(data)
print(f.readlines())
for index,line in enumerate(f.readlines()): # f.readlines()是一个列表,enumerate将列表变成一个由(下标,元素)的元组组成的新列表
if index == 9:
print("-----------我是分割线-------")
continue
print(line.strip())
for line in f.readlines()[:9]: # f.readlines()是一个列表
print(line.strip())
循环一:
for index,line in enumerate(f.readlines()): # f.readlines()是一个列表,enumerate将列表变成一个由(下标,元素)的元组组成的新列表
if index == 9:
print("-----------我是分割线-------")
continue
print(line.strip())
循环二:(推荐方式)
f = open("yesterday",'r',encoding='utf-8')
count = 0
for line in f: # 此时f不再是一个列表,而是一个迭代器。优点是内存占用少。
if count == 9:
print('--------分割线--------')
count += 1
continue
print(line)
count +=1
文件操作:
f = open("yesterday","r",encoding='utf-8')
print(f.tell()) # f.tell()查找指针的位置
print(f.readline()) # f.read(n)读n个字符
print(f.tell())
f.seek(0) # f.seek(n) 将指针回到n的位置
print(f.encoding) # f.encoding打印文件编码
print(f.fileno()) # 返回文件在内存中的编号
print(f.name) # 打印文件名字
print(f.isatty()) # 判断是否打开一个终端设备
print(f.seekable()) # 判断文件是否可移动指针。albe后缀是判断可用
print(f.flush()) # f.flush强制刷新,将缓存中的数据刷到硬盘中
f = open("yesterday", "a", encoding="utf-8")
f.truncate(20) # 截断函数,从文件开头开始截断但指定位置
f = open("yesterday2", 'r+', encoding='utf-8') # 文件句柄,读写。写是追加到文件的末尾。
f = open("yesterday2", 'a+', encoding='utf-8') # 文件句柄,追加读。写是追加到文件的末尾。
f = open("yesterday2", 'w+', encoding="utf-8") # 文件句柄,写读(不常用)。先创建文件再读取文件,文件还是不能修改,只能追加。
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("--------diao----------\n")
f.write("--------diao----------\n")
f.write("--------diao----------\n")
f.write("--------diao----------\n")
f.write("--------diao----------\n")
print(f.tell())
f.seek(10)
print(f.tell())
print(f.readline())
f.write("should be at the begining of the second line")
f.close()
f = open("yesterday2", 'rb') # 文件句柄,读二进制文件。python3.x网络传输只能用二进制,python2.x还能用字符。
f = open("yesterday2", 'wb') # 文件句柄,读二进制文件。python3.x网络传输只能用二进制,python2.x还能用字符。
# U 自动转换成liunx文件格式,表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)。rU,r+U
f.write("hello binary\n".encode())
f.close()
修改文件1
f = open("yesterday2", 'r', encoding="utf-8")
f_new = open("yesterday3", 'w', encoding="utf-8")
for line in f:
if "肆意的快乐等我" in line:
line = line.replace("肆意的快乐等我", "肆意的快乐等phoenix")
f_new.write(line)
f.close()
f_new.close()
with语句:
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1、with open('log', 'r') as f:
如此方式,当with代码块执行完毕时,内部会自动关闭释放文件资源。
在python2.7后,with支持同时对多个文件的上下文进行管理,即:
2、with open('log1') as obj,open('log2') as obj2:
修改文件2
with open("yesterday2", 'r', encoding="utf-8") as f,\
open("yesterday3", 'w', encoding="utf-8") as f_new:
for line in f:
if "肆意的快乐等我" in line:
line = line.replace("肆意的快乐等我", "肆意的快乐等phoenix")
f_new.write(line)
以上为修改文件的一种方式。