python基础-文件操作

时间:2022-03-27 18:03:23

一、文件操作

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • 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. 打开文件,得到文件句柄并赋值给一个变量
  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') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件 f.close() #关闭文件

打开文件的模式有:

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

读文件示例

法1:

1、先创建一个文件名称为:yesterday文本文件,内容如下:

 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
当我年少轻狂

读取文件

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige
#读取文件内容,并打印出来
data = open("yesterday",encoding="utf-8").read()
print(data)

读出上面那个文件里的内容

执行结果:

 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
当我年少轻狂

法2:

实验没有做成功。没有输出data2的结果

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #data = open("yesterday",encoding="utf-8").read()
#打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
f = open("yesterday",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置))
data = f.read()
data2 = f.read()
print(data)
print('--------------data2---------------',data2)

结果:

只输出data1的结果

实验没有做成功。没有输出data2的结果。


 读取和写入内容示例(错误的操作方法)

这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。(从删除库到跑路示例 !)

r   :读

w  :写

 # -*- coding:utf-8 -*-
#Author: nulige #这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。
#data = open("yesterday",encoding="utf-8").read()
#打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
#f = open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置))
f = open("yesterday","w",encoding="utf-8")
data = f.read()
print(data)
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的文件

内容如下:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #读文件或打开文件
#data = open("yesterday",encoding="utf-8").read()
f = open("yesterday",encoding="utf-8") #文件句柄
data = f.read()
print(data)

执行结果:

 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
当我年少轻狂

write创建一个文件名为:
yesterday2的新文件,并可以写入内容
 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'w',encoding="utf-8") #文件句柄
f.write("我爱北京*,\n") # write创建一个新文件,并可以写入内容
f.write("*前太阳升")

执行结果:

yesterday2.txt

 我爱北京*,
*前太阳升

追加文件示例

方法1:

1、先创建一个名称为:yesterday2空文件

2、再创建一个file_open.py的文件

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。
#data = open("yesterday",encoding="utf-8").read()
#打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
#f = open("yesterday","r",encoding="utf-8") #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置))
f = open("yesterday2","w",encoding="utf-8") f.write("我爱北京*,")
f.write("*上太阳升")

执行结果:

yesterday2 会在左边写入一个文件,然后双击那个文件,创建一个名称这yesterday2的文本文件。

并会往里面写入内容:

 我爱北京*,*上太阳升

方法二:

1、先创建一个名称为:yesterday2空文件

2、再创建一个file_open.py的文件

内容如下:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'a',encoding="utf-8") #文件句柄
#a = append 追加
f.write("我爱北京*.....\n")
f.write("*上太阳升....")
f.close()

执行结果:

会往里面追加内容并换行。换行符用\n 表示

 我爱北京*
*上太阳升
3 我爱北京*.....
*上太阳升....

用了a 追加方法,再去读取文件会报错 (只能追加,不能再去读取)

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #用了a 追加方法,再去读取文件会报错 (只能追加,不能再去读取)
f = open("yesterday2",'a',encoding="utf-8") #文件句柄
#a = append 追加 f.write("\nwhen i was young i listen to the radio\n")
data = f.read()
print(' read',data)

执行结果:

1 Traceback (most recent call last):
File "D:/python/day3/file_open.py", line 10, in <module>
data = f.read()
io.UnsupportedOperation: not readable

读取文件前5行示例

1、选创建一个文本文件,取名为yesterday2。

内容为:

 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
当我年少轻狂

2、实现读取文件前五行

法1:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #读取前5行
print(f.readline()) #读取一行,搞五次,就是读取五行,这个方法好笨哦!!!
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())

法2:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #用循环的方法,循环五次
f = open("yesterday2",'r',encoding="utf-8")
for i in range(5):
print(f.readline())

执行结果:

 Somehow, it seems the love I knew was always the most destructive kind

 不知为何,我经历的爱情总是最具毁灭性的的那种

 Yesterday when I was young

 昨日当我年少轻狂

 The taste of life was sweet

打印出文件所有内容

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") for line in f.readlines():
print(line)

执行结果:

 不知为何,我经历的爱情总是最具毁灭性的的那种

 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

 当我年少轻狂

用strip()  去掉空格和换行,打印出所有内容

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") for line in f.readlines():
print(line.strip())

执行结果:

 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
当我年少轻狂

打印第9行,不打印第10行示例

法一:不推荐使用,效率太低

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #打印第9行,不打印第10行
f = open("yesterday2",'r',encoding="utf-8")
for index, line in enumerate(f.readlines()):
if index == 9:
print('-----------我是分割线-----------')
continue
print(line.strip())

法2: 推荐使用,效率高

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #处理20G的文件,一行一行处理,内存中只占用一行的方法
f = open("yesterday2",'r',encoding="utf-8")
count = 0
for line in f:
if count == 9:
print('-----------我是分割线-----------')
count += 1
continue
print(line.strip())
count +=1

执行结果:

 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
10 -----------我是分割线----------- #没有打印第10行
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
当我年少轻狂

 python文件操作 seek(),tell()

seek():移动文件读取指针到指定位置

tell():返回文件读取指针的位置

ps:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8")
print(f.tell()) #按字符计数
#print(f.readline()) #按字符进行读取
#print(f.read(5)) #只读5个字符
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell()) #回到第几行,想回第几行,就输入数字几 f.seek(0) #回到第0行
f.seek(10) #回到第10行
print(f.readline())

执行结果:

 0
Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 168
t seems the love I knew was always the most destructive kind #从这行的前面位置开始读取

encoding 打印文件编码

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") #打印文件编码
print(f.encoding)

执行结果:

 utf-8

fileno() 返回文件句柄,在内存中的编号

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") #返回文件句柄,在内存中的编号
print(f.fileno())

执行结果:

 3

name  打印文件名称

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") #打印文件名字
print(f.name)

执行结果:

 yesterday2

isatty() 打印一个终端设备  (什么是终端设备呢,例如:打印机)

结果只会显示:False or true

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") #打印一个终端设备(用于打印机交互)
print(f.isatty())

执行结果:

 False

seekable  移动指针位置

备注:

# tty文件是不能移回去的,不是所有的都可以移回去的,只有字符串、二进制可以移回去。
 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r',encoding="utf-8") # tty文件是不能移回去的,不是所有的都可以移回去的,只有字符串、二进制可以移回去。
print(f.seekable)

执行结果:

 <built-in method seekable of _io.TextIOWrapper object at 0x01437430>

查看buffer

 #查看buffer  (本身buffer,也是内存中的临时文件)
print(dir(f.buffer) )

执果:

 ['__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了一下,才会保存到硬盘中去。

#刚写完一行内容,如果断电,他就没有写进去,断电内存中数据就会丢失。如果没有断电,数据还在内存的缓存中,需要刷新一下,才能写到硬盘中。

#内存有一个大小限制,需要达到这个大小,才会把内存缓存中的内容写到硬盘中。

python基础-文件操作

python基础-文件操作

在屏幕上面打印进度条

法一:

 打印一个#号,每次都会换行
>>>print("#")
#
>>>print("#")
#
>>>print("#")
# 那我们就不能用这种方法。需要用下面方法实现
>>>import sys
>>>sys.stdout.write(“#】”) #标准输出。输出到屏幕。
#
>>>sys.stdout.write(“####”)
####4
>>>sys.stdout.write(“########”)
########8

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import sys,time for i in range(50):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)

执行结果:

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

truncate 截断文件

如果你不写,就会把文件清空

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'w',encoding="utf-8")
f.truncate() #注意 ()里面没有写内容,会把文件清空

执行结果:

yesterday2.txt 中文件内容被清空

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'a',encoding="utf-8") #文件句柄
f.truncate(10)

执行结果:

yesterday2.txt 中文件内容被清空

 Somehow, i

移到第10位,截取20个字符

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'a',encoding="utf-8") #文件句柄
f.seek(10)
f.truncate(20)

执行结果:

yesterday2.txt 中文件内容

 Somehow, it seems th

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

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

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

  • rU
  • r+U

r+,可读写文件。【可读;可写;可追加】 (工作中经常用)

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 ,读写
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell()) #打印光标
f.write("------------------diao-------------------") 11 print(f.readline())

执行结果:

 Somehow, it seems the love I knew was always the most destructive kind

 不知为何,我经历的爱情总是最具毁灭性的的那种

 Yesterday when I was young

 168

写入yesterday2文件中的内容

 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
当我年少轻狂------------------diao-------------------

w+,写读 (工作中基本不用)

示例1:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #f = open("yesterday2",'r+',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-------------------")
print(f.readline())

执行结果:

往yesterday2文件中写入内容

 ------------------diao-------------------

示例2:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄
f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 #创建文件写4行
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n") #打印位置
print(f.tell()) #返回指针到第10行
f.seek(10) #打印出来
print(f.readline()) #写入下面这句话
f.write("should be at the begining of the second line") #关闭
f.close()

执行结果:

 ------------------diao------------------1
------------------diao------------------1 #没有办法在这行写,往前面写会不停覆盖原文件,要字符相等,否则会覆盖掉原文件。
------------------diao------------------1
------------------diao------------------1
should be at the begining of the second line

a+,同a

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #f = open("yesterday2",'r+',encoding="utf-8") #文件句柄 读写
#f = open("yesterday2",'w+',encoding="utf-8") #文件句柄 写读
f = open("yesterday2",'a+',encoding="utf-8") #文件句柄 追加读写
#创建文件写4行
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n")
f.write("------------------diao------------------1\n")
#打印位置
print(f.tell())
#返回指针到第10行
f.seek(10)
#打印出来
print(f.readline())
#写入下面这句话
f.write("should be at the begining of the second line")
#关闭
f.close()

执行结果:

 ------------------diao------------------1
------------------diao------------------1
------------------diao------------------1
------------------diao------------------1
should be at the begining of the second line

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

  • rb
  • wb
  • ab

打开二进制文件(网络传输的时候,就必须以二进制打开)

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'rb') #文件句柄 二进制文件
print(f.readline())
print(f.readline())
print(f.readline())

执行结果:

 b'------------------diao------------------1\r\n'
b'------------------diao------------------1\r\n'
b'------------------diao------------------1\r\n'

文件操作的二进制读写

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige f = open("yesterday2",'wb') #文件句柄 二进制文件
f.write("hello binary\n".encode())
f.close()

执行结果:

 hello binary

更改文件内容

1、先创建一个yesterday2的文件,内容如下:

 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
当我年少轻狂

2、先创建一个新文件,再读取文件内容,再更改其中某一行内容

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #先读取,再写入一行
f = open("yesterday2",'r',encoding="utf-8")
f_new = open("yesterday2.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()

执行结果:

会先创建一个 yesterday2.bak的文件,再更改其中某一行内容

 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
有那么多肆意的快乐等Alex享受
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
5 有那么多肆意的快乐等Alex享受
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
当我年少轻狂

通过变量传参的方式,实现修改文件某行内容

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import sys
#先读取,再写入一行
f = open("yesterday2",'r',encoding="utf-8")
f_new = open("yesterday2.bak",'w',encoding="utf-8") find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

 with open('log','r') as f:

     ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

 1
2
with open('log1') as obj1, open('log2') as obj2:
pass

ps:

为了避免打开文件后忘记关闭,不用再写关闭语句,自动会帮你关闭。

1、yesterday2文件内容

 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
当我年少轻狂

2、用with语句实现,文件自动关闭

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import sys
#先读取,再写入一行
# f = open("yesterday2",'r',encoding="utf-8") with open("yesterday2",'r',encoding="utf-8") as f:
for line in f:
print(line)

执行结果:

 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

 当我年少轻狂

同时打开多个文件的写法

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige import sys
#先读取,再写入一行
# f = open("yesterday2",'r',encoding="utf-8") with open("yesterday2",'r',encoding="utf-8") as f ,\
open("yesterday2", 'r', encoding="utf-8") as f2:
for line in f:
print(line)

执行结果:

 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

 当我年少轻狂

一、读取大文件的最后一行内容(例如:查看linux系统文件日志)

1、先创建一个日志文件

内容如下:

 2016/12/25 alex 干了什么事情
2016/12/26 alex 干了什么事情
2016/12/27 alex 干了什么事情
2016/12/28 alex 干了什么事情
2016/12/29 alex 干了什么事情
2016/12/30 sb 干了什么sb事情

2、实现读取文件最后一行内容

 f = open('日志文件', 'rb')

 for i in f:
offs = -10
while True:
f.seek(offs,2) # 从最后一行往前找
data = f.readlines() # 一行一行找
if len(data) > 1:
print('文件的最后一行是:%s' % (data[-1].decode('utf-8'))) # 读取文件最后一行
break
offs *= 2 #相当于两倍文件的内容中查找

执行结果:

 文件的最后一行是:2016/12/30  sb  干了什么sb事情

###############################文件操作复习##################################

1、写文件

 #写文件
f = open('a.txt','w',encoding='utf-8')
f.write('abc\n') #写入三行内容
f.write('adfdsssfsf\n')
f.write('adfdssfdf\n')
f.close()

执行结果:

会先创建一个a.txt的文件,内容如下:

 abc
adfdsssfsf
adfdssfdf

2、读文件

 f = open('a.txt','r',encoding='utf-8')
print(f.read())

执行结果:

 abc
adfdsssfsf
adfdssfdf

3、readlines 读成一个列表

 f = open('a.txt','r',encoding='utf-8')
print(f.readlines()) #通过可迭代协议实现的

执行结果:

 ['abc\n', 'adfdsssfsf\n', 'adfdssfdf\n']

4、readline 一次读取一行

 f = open('a.txt','r',encoding='utf-8')
print(f.readline())

执行结果:

 abc

5、for循环遍历的方式(结果会有空行)

 f =open('a.txt','r',encoding='utf-8')
for i in f:
print(i)

执行结果:

 abc

 adfdsssfsf

 adfdssfdf

6、for循环遍历的方式,去除空行

 f =open('a.txt','r',encoding='utf-8')
for i in f:
print(i,end='')

执行结果:

 abc
adfdsssfsf
adfdssfdf

7、for循环遍历 + readlines方式,去除空行

 f =open('a.txt','r',encoding='utf-8')
for i in f.readlines():
print(i.strip())

执行结果:

 abc
adfdsssfsf
adfdssfdf

8、二进制的方式读取,不需要加编码方式,

 f = open('a.txt','rb')
print(f.read())

执行结果:

 b'abc\r\nadfdsssfsf\r\nadfdssfdf\r\n'

9、二进制读取,decode编码出结果

 f = open('a.txt','rb')
data = f.read()
data = data.decode('utf-8')
print(data)

执行结果:

 abc
adfdsssfsf
adfdssfdf

10、把a.txt文件中,含有a的内容替换成0

a.txt文件内容

 abc
adfdsssfsf
adfdssfdf

代码:

 import os
fr = open('a.txt','r',encoding='utf-8')
fw = open('b.txt','w',encoding='utf-8') for i in fr:
if 'a' in i:
y = i.replace('a','')
fw.write(y) fr.close()
fw.close() os.rename('a.txt','a.bak') #先把a.txt备份
os.rename('b.txt','a.txt') #再把b.txt重命名为a.txt
os.remove('a.bak') #再删除备份的a.bak

执行结果:

 0bc              #把a全部替换成0
0dfdsssfsf
0dfdssfdf

11、把b.txt里面a替换成0 和 s替换成5

a.txt里面的内容

 abc
adfdsssfsf
adfdssfdf

b.txt里面的内容

 abc
adfdsssfsf
adfdssfdf

代码:

 with open('a.txt','r',encoding='utf-8') as fr,\
open('b.txt','w',encoding='utf-8') as fw:
for i in fr:
if 'a' in i:
i = i.replace('a','') #把b.txt里面a替换成0
if 's' in i:
i = i.replace('s','') #把b.txt里面s替换成5
fw.write(i)

执行结果:

b.txt文件内容

 0bc          #a替换成0
0dfd555f5f #s替换成5
0dfd55fdf

12、r+ 先读再写 (

实现先读出列表,再写把a替换成6

先创建一个a.txt,内容如下:

 abc
adfd555f5f
adfd55fdf

代码:

 with open('a.txt','r+',encoding='utf-8') as fr:
a=fr.readlines()
print(a)
fr.seek(0)
for i in a:
if 'a' in i:
y = i.replace('a','')
fr.write(y)

执行结果:

 #先读出列表

 ['abc\n', 'adfdsssfsf\n', 'adfdssfdf\n']

再把a替换成6, 替换后的a.txt内容的结果:

 6bc
6dfdsssfsf
6dfdssfdf

13、字符串转成二进制

方法一:

 b = '12345gdfafdsa'.encode()
print(b)

执行结果:

 b'12345gdfafdsa'

方法二:

 aa = 'fsdfdsfssdsfds'
print(bytes(aa,encoding='gbk'))

执行结果:

 b'fsdfdsfssdsfds'