python基础教程-文件操作
来源:互联网 发布:清华大学材料学院知乎 编辑:程序博客网 时间:2024/05/16 04:38
一、文件操作
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
- w,只写模式【不可读;不存在则创建;存在则清空内容】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
Table 文件对象方法
方法描述f.close()关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。f.fileno()获得文件描述符,是一个数字f.flush()刷新输出缓存f.isatty()如果文件是一个交互终端,则返回True,否则返回False。f.read([count])读出文件,如果有count,则读出count个字节。f.readline()读出一行信息。f.readlines()读出所有行,也就是读出整个文件的信息。f.seek(offset[,where])把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。f.tell()获得文件指针位置。f.truncate([size])截取文件,使文件的大小为size。f.write(string)把string字符串写入文件。f.writelines(list)把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。
read(3)代表读取3个字符,其余的文件内光标移动是以字节为单位,如:seek,tell,read,truncate
f.flush() #讲文件内容从内存刷到硬盘(python3.x)
f.closed #文件如果关闭则返回True
f.encoding #查看使用open打开文件的编码
f.tell() #查看文件处理当前的光标位置
f.seek(3) #从开头开始算,将光标移动到第三个字节
f.truncate(10) #从开头开始算,将文件只保留从0-10个字节的内容,文件必须以写方式打开,但是w和w+除外。
对文件操作的流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
示例
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
基本操作
1 f = open('lyrics') #打开文件2 first_line = f.readline()3 print('first line:',first_line) #读一行4 print('我是分隔线'.center(50,'-'))5 data = f.read()# 读取剩下的所有内容,文件大时不要用6 print(data) #打印文件7 8 f.close() #关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
读文件示例
法1:
1、先创建一个文件名称为:yesterday文本文件,内容如下:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
读取文件
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 #读取文件内容,并打印出来5 data = open("yesterday",encoding="utf-8").read()6 print(data)
读出上面那个文件里的内容
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
法2:
实验没有做成功。没有输出data2的结果
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #data = open("yesterday",encoding="utf-8").read() 6 #打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值 7 f = open("yesterday",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置)) 8 data = f.read() 9 data2 = f.read()10 print(data)11 print('--------------data2---------------',data2)
结果:
只输出data1的结果
实验没有做成功。没有输出data2的结果。
读取和写入内容示例(错误的操作方法)
这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。(从删除库到跑路示例 !)
r :读
w :写
1 # -*- coding:utf-8 -*- 2 #Author: nulige 3 4 #这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。 5 #data = open("yesterday",encoding="utf-8").read() 6 #打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值 7 #f = open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置)) 8 f = open("yesterday","w",encoding="utf-8") 9 data = f.read()10 print(data)11 f.write("我爱北京天安门")
执行结果:
会报错的,不能同时又读又写
1 Traceback (most recent call last):2 File "D:/python/day3/file_open.py", line 10, in <module>3 data = f.read()4 io.UnsupportedOperation: not readable
查看yesterday文本文件中的内容发现,内容全被清空啦。
(文件内没有内容)
往文件中写入内容
1、先创建一个文件名称为:yesterday文本文件,内容为上面那首歌。
2、再创建一个file_open.py的文件
内容如下:
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 #读文件或打开文件6 #data = open("yesterday",encoding="utf-8").read()7 f = open("yesterday",encoding="utf-8") #文件句柄8 data = f.read()9 print(data)
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
write创建一个文件名为:yesterday2的新文件,并可以写入内容
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'w',encoding="utf-8") #文件句柄6 f.write("我爱北京天安门,\n") # write创建一个新文件,并可以写入内容7 f.write("天安门前太阳升")
执行结果:
yesterday2.txt
1 我爱北京天安门,2 天安门前太阳升
追加文件示例
方法1:
1、先创建一个名称为:yesterday2空文件
2、再创建一个file_open.py的文件
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。 6 #data = open("yesterday",encoding="utf-8").read() 7 #打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值 8 #f = open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置)) 9 f = open("yesterday2","w",encoding="utf-8")10 11 f.write("我爱北京天安门,")12 f.write("天安门上太阳升")
执行结果:
yesterday2 会在左边写入一个文件,然后双击那个文件,创建一个名称这yesterday2的文本文件。
并会往里面写入内容:
1 我爱北京天安门,天安门上太阳升
方法二:
1、先创建一个名称为:yesterday2空文件
2、再创建一个file_open.py的文件
内容如下:
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'a',encoding="utf-8") #文件句柄6 #a = append 追加7 f.write("我爱北京天安门.....\n")8 f.write("天安门上太阳升....")9 f.close()
执行结果:
会往里面追加内容并换行。换行符用\n 表示
1 我爱北京天安门2 天安门上太阳升3 我爱北京天安门.....4 天安门上太阳升....
用了a 追加方法,再去读取文件会报错 (只能追加,不能再去读取)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #用了a 追加方法,再去读取文件会报错 (只能追加,不能再去读取) 6 f = open("yesterday2",'a',encoding="utf-8") #文件句柄 7 #a = append 追加 8 9 f.write("\nwhen i was young i listen to the radio\n")10 data = f.read()11 print(' read',data)
执行结果:
1 Traceback (most recent call last):2 File "D:/python/day3/file_open.py", line 10, in <module>3 data = f.read()4 io.UnsupportedOperation: not readable
读取文件前5行示例
1、选创建一个文本文件,取名为yesterday2。
内容为:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
2、实现读取文件前五行
法1:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #读取前5行 6 print(f.readline()) #读取一行,搞五次,就是读取五行,这个方法好笨哦!!! 7 print(f.readline()) 8 print(f.readline()) 9 print(f.readline())10 print(f.readline())
法2:
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 #用循环的方法,循环五次6 f = open("yesterday2",'r',encoding="utf-8")7 for i in range(5):8 print(f.readline())
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind2 3 不知为何,我经历的爱情总是最具毁灭性的的那种4 5 Yesterday when I was young6 7 昨日当我年少轻狂8 9 The taste of life was sweet
打印出文件所有内容
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 for line in f.readlines():8 print(line)
执行结果:
1 不知为何,我经历的爱情总是最具毁灭性的的那种 2 3 Yesterday when I was young 4 5 昨日当我年少轻狂 6 7 The taste of life was sweet 8 9 生命的滋味是甜的 10 11 As rain upon my tongue 12 13 就如舌尖上的雨露 14 15 I teased at life as if it were a foolish game 16 17 我戏弄生命 视其为愚蠢的游戏 18 19 The way the evening breeze 20 21 就如夜晚的微风 22 23 May tease the candle flame 24 25 逗弄蜡烛的火苗 26 27 The thousand dreams I dreamed 28 29 我曾千万次梦见 30 31 The splendid things I planned 32 33 那些我计划的绚丽蓝图 34 35 I always built to last on weak and shifting sand 36 37 但我总是将之建筑在易逝的流沙上 38 39 I lived by night and shunned the naked light of day 40 41 我夜夜笙歌 逃避白昼赤裸的阳光 42 43 And only now I see how the time ran away 44 45 事到如今我才看清岁月是如何匆匆流逝 46 47 Yesterday when I was young 48 49 昨日当我年少轻狂 50 51 So many lovely songs were waiting to be sung 52 53 有那么多甜美的曲儿等我歌唱 54 55 So many wild pleasures lay in store for me 56 57 有那么多肆意的快乐等我享受 58 59 And so much pain my eyes refused to see 60 61 还有那么多痛苦 我的双眼却视而不见 62 63 I ran so fast that time and youth at last ran out 64 65 我飞快地奔走 最终时光与青春消逝殆尽 66 67 I never stopped to think what life was all about 68 69 我从未停下脚步去思考生命的意义 70 71 And every conversation that I can now recall 72 73 如今回想起的所有对话 74 75 Concerned itself with me and nothing else at all 76 77 除了和我相关的 什么都记不得了 78 79 The game of love I played with arrogance and pride 80 81 我用自负和傲慢玩着爱情的游戏 82 83 And every flame I lit too quickly, quickly died 84 85 所有我点燃的火焰都熄灭得太快 86 87 The friends I made all somehow seemed to slip away 88 89 所有我交的朋友似乎都不知不觉地离开了 90 91 And only now I'm left alone to end the play, yeah 92 93 只剩我一个人在台上来结束这场闹剧 94 95 Oh, yesterday when I was young 96 97 噢 昨日当我年少轻狂 98 99 So many, many songs were waiting to be sung100 101 有那么那么多甜美的曲儿等我歌唱102 103 So many wild pleasures lay in store for me104 105 有那么多肆意的快乐等我享受106 107 And so much pain my eyes refused to see108 109 还有那么多痛苦 我的双眼却视而不见110 111 There are so many songs in me that won't be sung112 113 我有太多歌曲永远不会被唱起114 115 I feel the bitter taste of tears upon my tongue116 117 我尝到了舌尖泪水的苦涩滋味118 119 The time has come for me to pay for yesterday120 121 终于到了付出代价的时间 为了昨日122 123 When I was young124 125 当我年少轻狂
用strip() 去掉空格和换行,打印出所有内容
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 for line in f.readlines():8 print(line.strip())
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
打印第9行,不打印第10行示例
法一:不推荐使用,效率太低
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #打印第9行,不打印第10行 6 f = open("yesterday2",'r',encoding="utf-8") 7 for index, line in enumerate(f.readlines()): 8 if index == 9: 9 print('-----------我是分割线-----------')10 continue11 print(line.strip())
法2: 推荐使用,效率高
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #处理20G的文件,一行一行处理,内存中只占用一行的方法 6 f = open("yesterday2",'r',encoding="utf-8") 7 count = 0 8 for line in f: 9 if count == 9:10 print('-----------我是分割线-----------')11 count += 112 continue13 print(line.strip())14 count +=1
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 -----------我是分割线----------- #没有打印第10行11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
python文件操作 seek(),tell()
seek():移动文件读取指针到指定位置
tell():返回文件读取指针的位置
ps:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 f = open("yesterday2",'r',encoding="utf-8") 6 print(f.tell()) #按字符计数 7 #print(f.readline()) #按字符进行读取 8 #print(f.read(5)) #只读5个字符 9 print(f.readline())10 print(f.readline())11 print(f.readline())12 print(f.tell())13 14 #回到第几行,想回第几行,就输入数字几15 16 f.seek(0) #回到第0行17 f.seek(10) #回到第10行18 print(f.readline())
执行结果:
1 02 Somehow, it seems the love I knew was always the most destructive kind3 4 不知为何,我经历的爱情总是最具毁灭性的的那种5 6 Yesterday when I was young7 8 1689 t seems the love I knew was always the most destructive kind #从这行的前面位置开始读取
encoding 打印文件编码
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 #打印文件编码8 print(f.encoding)
执行结果:
1 utf-8
fileno() 返回文件句柄,在内存中的编号
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 #返回文件句柄,在内存中的编号8 print(f.fileno())
执行结果:
1 3
name 打印文件名称
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 #打印文件名字8 print(f.name)
执行结果:
1 yesterday2
isatty() 打印一个终端设备 (什么是终端设备呢,例如:打印机)
结果只会显示:False or true
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 #打印一个终端设备(用于打印机交互)8 print(f.isatty())
执行结果:
1 False
seekable 移动指针位置
备注:
# tty文件是不能移回去的,不是所有的都可以移回去的,只有字符串、二进制可以移回去。
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 #Author: nulige4 5 f = open("yesterday2",'r',encoding="utf-8")6 7 # tty文件是不能移回去的,不是所有的都可以移回去的,只有字符串、二进制可以移回去。8 print(f.seekable)
执行结果:
1 <built-in method seekable of _io.TextIOWrapper object at 0x01437430>
查看buffer
1 #查看buffer (本身buffer,也是内存中的临时文件)2 print(dir(f.buffer) )
执果:
1 ['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_dealloc_warn', '_finalizing', 'close', 'closed', 'detach', 'fileno', 'flush', 'isatty', 'mode', 'name', 'peek', 'raw', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']
flush 刷新
说明:写入的内容是存放在电脑的缓存中的,只有flush了一下,才会保存到硬盘中去。
#刚写完一行内容,如果断电,他就没有写进去,断电内存中数据就会丢失。如果没有断电,数据还在内存的缓存中,需要刷新一下,才能写到硬盘中。
#内存有一个大小限制,需要达到这个大小,才会把内存缓存中的内容写到硬盘中。
在屏幕上面打印进度条
法一:
1 打印一个#号,每次都会换行 2 >>>print("#") 3 # 4 >>>print("#") 5 # 6 >>>print("#") 7 # 8 9 那我们就不能用这种方法。需要用下面方法实现10 >>>import sys11 >>>sys.stdout.write(“#】”) #标准输出。输出到屏幕。12 #1213 >>>sys.stdout.write(“####”) 14 ####415 >>>sys.stdout.write(“########”) 16 ########8
法二:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 import sys,time 6 7 for i in range(50): 8 sys.stdout.write("#") 9 sys.stdout.flush()10 time.sleep(0.1)
执行结果:
1 ##################################################
truncate 截断文件
如果你不写,就会把文件清空
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*- 3 #Author: nulige4 5 f = open("yesterday2",'w',encoding="utf-8")6 f.truncate() #注意 ()里面没有写内容,会把文件清空
执行结果:
yesterday2.txt 中文件内容被清空
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*- 3 #Author: nulige4 5 f = open("yesterday2",'a',encoding="utf-8") #文件句柄6 f.truncate(10)
执行结果:
yesterday2.txt 中文件内容被清空
1 Somehow, i
移到第10位,截取20个字符
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*- 3 #Author: nulige4 5 f = open("yesterday2",'a',encoding="utf-8") #文件句柄6 f.seek(10)7 f.truncate(20)
执行结果:
yesterday2.txt 中文件内容
1 Somehow, it seems th
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
r+,可读写文件。【可读;可写;可追加】 (工作中经常用)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 ,读写 6 print(f.readline()) 7 print(f.readline()) 8 print(f.readline()) 9 print(f.tell()) #打印光标10 f.write("------------------diao-------------------")11 print(f.readline())
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind2 3 不知为何,我经历的爱情总是最具毁灭性的的那种4 5 Yesterday when I was young6 7 168
写入yesterday2文件中的内容
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂------------------diao-------------------
w+,写读 (工作中基本不用)
示例1:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 6 f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 7 print(f.readline()) 8 print(f.readline()) 9 print(f.readline())10 print(f.tell()) #打印光标11 f.write("------------------diao-------------------")12 print(f.readline())
执行结果:
往yesterday2文件中写入内容
1 ------------------diao-------------------
示例2:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 6 f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 7 8 #创建文件写4行 9 f.write("------------------diao------------------1\n")10 f.write("------------------diao------------------1\n")11 f.write("------------------diao------------------1\n")12 f.write("------------------diao------------------1\n")13 14 #打印位置15 print(f.tell())16 17 #返回指针到第10行18 f.seek(10)19 20 #打印出来21 print(f.readline())22 23 #写入下面这句话24 f.write("should be at the begining of the second line")25 26 #关闭27 f.close()
执行结果:
1 ------------------diao------------------12 ------------------diao------------------1 #没有办法在这行写,往前面写会不停覆盖原文件,要字符相等,否则会覆盖掉原文件。3 ------------------diao------------------14 ------------------diao------------------15 should be at the begining of the second line
a+,同a
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 读写 6 #f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 写读 7 f = open("yesterday2",'a+',encoding="utf-8") #文件句柄 追加读写 8 #创建文件写4行 9 f.write("------------------diao------------------1\n")10 f.write("------------------diao------------------1\n")11 f.write("------------------diao------------------1\n")12 f.write("------------------diao------------------1\n")13 #打印位置14 print(f.tell())15 #返回指针到第10行16 f.seek(10)17 #打印出来18 print(f.readline())19 #写入下面这句话20 f.write("should be at the begining of the second line")21 #关闭22 f.close()
执行结果:
1 ------------------diao------------------12 ------------------diao------------------13 ------------------diao------------------14 ------------------diao------------------15 should be at the begining of the second line
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
打开二进制文件(网络传输的时候,就必须以二进制打开)
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*- 3 #Author: nulige4 5 f = open("yesterday2",'rb') #文件句柄 二进制文件6 print(f.readline())7 print(f.readline())8 print(f.readline())
执行结果:
1 b'------------------diao------------------1\r\n'2 b'------------------diao------------------1\r\n'3 b'------------------diao------------------1\r\n'
文件操作的二进制读写
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*- 3 #Author: nulige4 5 f = open("yesterday2",'wb') #文件句柄 二进制文件6 f.write("hello binary\n".encode())7 f.close()
执行结果:
1 hello binary
更改文件内容
1、先创建一个yesterday2的文件,内容如下:
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
2、先创建一个新文件,再读取文件内容,再更改其中某一行内容
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 #先读取,再写入一行 6 f = open("yesterday2",'r',encoding="utf-8") 7 f_new = open("yesterday2.bak",'w',encoding="utf-8") 8 9 for line in f:10 if "肆意的快乐等我享受" in line:11 line =line.replace("肆意的快乐等我享受","肆意的快乐等Alex享受")12 f_new.write(line)13 f.close()14 f_new.close()
执行结果:
会先创建一个 yesterday2.bak的文件,再更改其中某一行内容
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等Alex享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等Alex享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
通过变量传参的方式,实现修改文件某行内容
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 import sys 6 #先读取,再写入一行 7 f = open("yesterday2",'r',encoding="utf-8") 8 f_new = open("yesterday2.bak",'w',encoding="utf-8") 9 10 find_str = sys.argv[1]11 replace_str = sys.argv[2]12 for line in f:13 if find_str in line:14 line = line.replace(find_str,replace_str)15 f_new.write(line)16 f.close()17 f_new.close()
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1 with open('log','r') as f:2 3 ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1 12 23 with open('log1') as obj1, open('log2') as obj2:4 pass
ps:
为了避免打开文件后忘记关闭,不用再写关闭语句,自动会帮你关闭。
1、yesterday2文件内容
1 Somehow, it seems the love I knew was always the most destructive kind 2 不知为何,我经历的爱情总是最具毁灭性的的那种 3 Yesterday when I was young 4 昨日当我年少轻狂 5 The taste of life was sweet 6 生命的滋味是甜的 7 As rain upon my tongue 8 就如舌尖上的雨露 9 I teased at life as if it were a foolish game10 我戏弄生命 视其为愚蠢的游戏11 The way the evening breeze12 就如夜晚的微风13 May tease the candle flame14 逗弄蜡烛的火苗15 The thousand dreams I dreamed16 我曾千万次梦见17 The splendid things I planned18 那些我计划的绚丽蓝图19 I always built to last on weak and shifting sand20 但我总是将之建筑在易逝的流沙上21 I lived by night and shunned the naked light of day22 我夜夜笙歌 逃避白昼赤裸的阳光23 And only now I see how the time ran away24 事到如今我才看清岁月是如何匆匆流逝25 Yesterday when I was young26 昨日当我年少轻狂27 So many lovely songs were waiting to be sung28 有那么多甜美的曲儿等我歌唱29 So many wild pleasures lay in store for me30 有那么多肆意的快乐等我享受31 And so much pain my eyes refused to see32 还有那么多痛苦 我的双眼却视而不见33 I ran so fast that time and youth at last ran out34 我飞快地奔走 最终时光与青春消逝殆尽35 I never stopped to think what life was all about36 我从未停下脚步去思考生命的意义37 And every conversation that I can now recall38 如今回想起的所有对话39 Concerned itself with me and nothing else at all40 除了和我相关的 什么都记不得了41 The game of love I played with arrogance and pride42 我用自负和傲慢玩着爱情的游戏43 And every flame I lit too quickly, quickly died44 所有我点燃的火焰都熄灭得太快45 The friends I made all somehow seemed to slip away46 所有我交的朋友似乎都不知不觉地离开了47 And only now I'm left alone to end the play, yeah48 只剩我一个人在台上来结束这场闹剧49 Oh, yesterday when I was young50 噢 昨日当我年少轻狂51 So many, many songs were waiting to be sung52 有那么那么多甜美的曲儿等我歌唱53 So many wild pleasures lay in store for me54 有那么多肆意的快乐等我享受55 And so much pain my eyes refused to see56 还有那么多痛苦 我的双眼却视而不见57 There are so many songs in me that won't be sung58 我有太多歌曲永远不会被唱起59 I feel the bitter taste of tears upon my tongue60 我尝到了舌尖泪水的苦涩滋味61 The time has come for me to pay for yesterday62 终于到了付出代价的时间 为了昨日63 When I was young64 当我年少轻狂
2、用with语句实现,文件自动关闭
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 import sys 6 #先读取,再写入一行 7 # f = open("yesterday2",'r',encoding="utf-8") 8 9 with open("yesterday2",'r',encoding="utf-8") as f:10 for line in f:11 print(line)
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 3 不知为何,我经历的爱情总是最具毁灭性的的那种 4 5 Yesterday when I was young 6 7 昨日当我年少轻狂 8 9 The taste of life was sweet 10 11 生命的滋味是甜的 12 13 As rain upon my tongue 14 15 就如舌尖上的雨露 16 17 I teased at life as if it were a foolish game 18 19 我戏弄生命 视其为愚蠢的游戏 20 21 The way the evening breeze 22 23 就如夜晚的微风 24 25 May tease the candle flame 26 27 逗弄蜡烛的火苗 28 29 The thousand dreams I dreamed 30 31 我曾千万次梦见 32 33 The splendid things I planned 34 35 那些我计划的绚丽蓝图 36 37 I always built to last on weak and shifting sand 38 39 但我总是将之建筑在易逝的流沙上 40 41 I lived by night and shunned the naked light of day 42 43 我夜夜笙歌 逃避白昼赤裸的阳光 44 45 And only now I see how the time ran away 46 47 事到如今我才看清岁月是如何匆匆流逝 48 49 Yesterday when I was young 50 51 昨日当我年少轻狂 52 53 So many lovely songs were waiting to be sung 54 55 有那么多甜美的曲儿等我歌唱 56 57 So many wild pleasures lay in store for me 58 59 有那么多肆意的快乐等我享受 60 61 And so much pain my eyes refused to see 62 63 还有那么多痛苦 我的双眼却视而不见 64 65 I ran so fast that time and youth at last ran out 66 67 我飞快地奔走 最终时光与青春消逝殆尽 68 69 I never stopped to think what life was all about 70 71 我从未停下脚步去思考生命的意义 72 73 And every conversation that I can now recall 74 75 如今回想起的所有对话 76 77 Concerned itself with me and nothing else at all 78 79 除了和我相关的 什么都记不得了 80 81 The game of love I played with arrogance and pride 82 83 我用自负和傲慢玩着爱情的游戏 84 85 And every flame I lit too quickly, quickly died 86 87 所有我点燃的火焰都熄灭得太快 88 89 The friends I made all somehow seemed to slip away 90 91 所有我交的朋友似乎都不知不觉地离开了 92 93 And only now I'm left alone to end the play, yeah 94 95 只剩我一个人在台上来结束这场闹剧 96 97 Oh, yesterday when I was young 98 99 噢 昨日当我年少轻狂100 101 So many, many songs were waiting to be sung102 103 有那么那么多甜美的曲儿等我歌唱104 105 So many wild pleasures lay in store for me106 107 有那么多肆意的快乐等我享受108 109 And so much pain my eyes refused to see110 111 还有那么多痛苦 我的双眼却视而不见112 113 There are so many songs in me that won't be sung114 115 我有太多歌曲永远不会被唱起116 117 I feel the bitter taste of tears upon my tongue118 119 我尝到了舌尖泪水的苦涩滋味120 121 The time has come for me to pay for yesterday122 123 终于到了付出代价的时间 为了昨日124 125 When I was young126 127 当我年少轻狂
同时打开多个文件的写法
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 import sys 6 #先读取,再写入一行 7 # f = open("yesterday2",'r',encoding="utf-8") 8 9 with open("yesterday2",'r',encoding="utf-8") as f ,\10 open("yesterday2", 'r', encoding="utf-8") as f2:11 for line in f:12 print(line)
执行结果:
1 Somehow, it seems the love I knew was always the most destructive kind 2 3 不知为何,我经历的爱情总是最具毁灭性的的那种 4 5 Yesterday when I was young 6 7 昨日当我年少轻狂 8 9 The taste of life was sweet 10 11 生命的滋味是甜的 12 13 As rain upon my tongue 14 15 就如舌尖上的雨露 16 17 I teased at life as if it were a foolish game 18 19 我戏弄生命 视其为愚蠢的游戏 20 21 The way the evening breeze 22 23 就如夜晚的微风 24 25 May tease the candle flame 26 27 逗弄蜡烛的火苗 28 29 The thousand dreams I dreamed 30 31 我曾千万次梦见 32 33 The splendid things I planned 34 35 那些我计划的绚丽蓝图 36 37 I always built to last on weak and shifting sand 38 39 但我总是将之建筑在易逝的流沙上 40 41 I lived by night and shunned the naked light of day 42 43 我夜夜笙歌 逃避白昼赤裸的阳光 44 45 And only now I see how the time ran away 46 47 事到如今我才看清岁月是如何匆匆流逝 48 49 Yesterday when I was young 50 51 昨日当我年少轻狂 52 53 So many lovely songs were waiting to be sung 54 55 有那么多甜美的曲儿等我歌唱 56 57 So many wild pleasures lay in store for me 58 59 有那么多肆意的快乐等我享受 60 61 And so much pain my eyes refused to see 62 63 还有那么多痛苦 我的双眼却视而不见 64 65 I ran so fast that time and youth at last ran out 66 67 我飞快地奔走 最终时光与青春消逝殆尽 68 69 I never stopped to think what life was all about 70 71 我从未停下脚步去思考生命的意义 72 73 And every conversation that I can now recall 74 75 如今回想起的所有对话 76 77 Concerned itself with me and nothing else at all 78 79 除了和我相关的 什么都记不得了 80 81 The game of love I played with arrogance and pride 82 83 我用自负和傲慢玩着爱情的游戏 84 85 And every flame I lit too quickly, quickly died 86 87 所有我点燃的火焰都熄灭得太快 88 89 The friends I made all somehow seemed to slip away 90 91 所有我交的朋友似乎都不知不觉地离开了 92 93 And only now I'm left alone to end the play, yeah 94 95 只剩我一个人在台上来结束这场闹剧 96 97 Oh, yesterday when I was young 98 99 噢 昨日当我年少轻狂100 101 So many, many songs were waiting to be sung102 103 有那么那么多甜美的曲儿等我歌唱104 105 So many wild pleasures lay in store for me106 107 有那么多肆意的快乐等我享受108 109 And so much pain my eyes refused to see110 111 还有那么多痛苦 我的双眼却视而不见112 113 There are so many songs in me that won't be sung114 115 我有太多歌曲永远不会被唱起116 117 I feel the bitter taste of tears upon my tongue118 119 我尝到了舌尖泪水的苦涩滋味120 121 The time has come for me to pay for yesterday122 123 终于到了付出代价的时间 为了昨日124 125 When I was young126 127 当我年少轻狂
一、读取大文件的最后一行内容(例如:查看linux系统文件日志)
1、先创建一个日志文件
内容如下:
1 2016/12/25 alex 干了什么事情2 2016/12/26 alex 干了什么事情3 2016/12/27 alex 干了什么事情4 2016/12/28 alex 干了什么事情5 2016/12/29 alex 干了什么事情6 2016/12/30 sb 干了什么sb事情
2、实现读取文件最后一行内容
1 f = open('日志文件', 'rb') 2 3 for i in f: 4 offs = -10 5 while True: 6 f.seek(offs,2) # 从最后一行往前找 7 data = f.readlines() # 一行一行找 8 if len(data) > 1: 9 print('文件的最后一行是:%s' % (data[-1].decode('utf-8'))) # 读取文件最后一行10 break11 offs *= 2 #相当于两倍文件的内容中查找
执行结果:
1 文件的最后一行是:2016/12/30 sb 干了什么sb事情
- python基础教程-文件操作
- Python操作Mysql基础教程
- python 基础教程之文件
- Python 3基础教程22-单个列表操作
- linux基础教程-----目录文件操作(1)
- linux基础教程-----目录文件操作(2)
- 《Python基础教程》 第六章 文件处理笔记
- 【Python基础教程】第11章 文件
- Python 3基础教程13-写入文件
- Python 3基础教程15-读文件内容
- Python 3基础教程24-读取csv文件
- python基础教程[1]:删除文件及文件夹
- python基础教程[2]:复制文件及文件夹
- Python基础教程
- Python基础教程
- Python基础教程
- Python 基础教程
- python 基础教程
- 如何重新修改sourceinght的注册序列号
- VS2008的常见问题
- MimeMessageHelper使用流发送带附件的邮件报错
- 山科大 oj 提取缩略词
- 会话技术
- python基础教程-文件操作
- 查看硬件配置命令(ubuntu示例)
- java读写Properties属性文件公用方法
- 做一个自己的MVC框架[php]
- NUMA架构的CPU
- 输入一个数插入有序数组中
- 微信分享 解决留在微信时没有回调结果的问题(不保证所有的都成功)
- php 字符串大小写转换
- Java使用HtmlParse提取标签中的值