python基础-文件操作

一、文件操作

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

打开文件的模式有:

  • 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. 关闭文件

示例

 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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

基本操作 

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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

读取文件

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 #读取文件内容,并打印出来
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

 

 法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 python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
View Code

write创建一个文件名为:
yesterday2的新文件,并可以写入内容
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
View Code

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 python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 kind
2 
3 不知为何,我经历的爱情总是最具毁灭性的的那种
4 
5 Yesterday when I was young
6 
7 昨日当我年少轻狂
8 
9 The taste of life was sweet

 打印出文件所有内容

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 sung
100 
101 有那么那么多甜美的曲儿等我歌唱
102 
103 So many wild pleasures lay in store for me
104 
105 有那么多肆意的快乐等我享受
106 
107 And so much pain my eyes refused to see
108 
109 还有那么多痛苦 我的双眼却视而不见
110 
111 There are so many songs in me that won't be sung
112 
113 我有太多歌曲永远不会被唱起
114 
115 I feel the bitter taste of tears upon my tongue
116 
117 我尝到了舌尖泪水的苦涩滋味
118 
119 The time has come for me to pay for yesterday
120 
121 终于到了付出代价的时间 为了昨日
122 
123 When I was young
124 
125 当我年少轻狂
View Code

 

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

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
View Code

 

打印第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         continue
11     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 += 1
12         continue
13     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 game
10 -----------我是分割线-----------     #没有打印第10行
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

 


 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 0
2 Somehow, it seems the love I knew was always the most destructive kind
3 
4 不知为何,我经历的爱情总是最具毁灭性的的那种
5 
6 Yesterday when I was young
7 
8 168
9 t seems the love I knew was always the most destructive kind    #从这行的前面位置开始读取

 

encoding 打印文件编码

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

执行结果:

1 utf-8

 

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

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

执行结果:

1 3

 

name  打印文件名称

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

执行结果:

1 yesterday2

 

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

结果只会显示:False or true

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

执行结果:

1 False

 

seekable  移动指针位置

备注:

# tty文件是不能移回去的,不是所有的都可以移回去的,只有字符串、二进制可以移回去。

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3 #Author: nulige
4 
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 sys
11 >>>sys.stdout.write(“#】”)    #标准输出。输出到屏幕。
12 #12
13 >>>sys.stdout.write(“####”)    
14 ####4
15 >>>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 python
2 # -*- coding:utf-8 -*-      
3 #Author: nulige
4 
5 f = open("yesterday2",'w',encoding="utf-8")
6 f.truncate()   #注意 ()里面没有写内容,会把文件清空

执行结果:

yesterday2.txt 中文件内容被清空

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

执行结果:

yesterday2.txt 中文件内容被清空

1 Somehow, i

 

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

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-      
3 #Author: nulige
4 
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 kind
2 
3 不知为何,我经历的爱情总是最具毁灭性的的那种
4 
5 Yesterday when I was young
6 
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂------------------diao-------------------
View Code

 

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------------------1
2 ------------------diao------------------1    #没有办法在这行写,往前面写会不停覆盖原文件,要字符相等,否则会覆盖掉原文件。
3 ------------------diao------------------1
4 ------------------diao------------------1
5 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------------------1
2 ------------------diao------------------1
3 ------------------diao------------------1
4 ------------------diao------------------1
5 should be at the begining of the second line

 


 

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

  • rb
  • wb
  • ab

 

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

1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-      
3 #Author: nulige
4 
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 python
2 # -*- coding:utf-8 -*-      
3 #Author: nulige
4 
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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

 

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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等Alex享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等Alex享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂

 

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

 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 1
2 2
3 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 game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
View Code

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 sung
102 
103 有那么那么多甜美的曲儿等我歌唱
104 
105 So many wild pleasures lay in store for me
106 
107 有那么多肆意的快乐等我享受
108 
109 And so much pain my eyes refused to see
110 
111 还有那么多痛苦 我的双眼却视而不见
112 
113 There are so many songs in me that won't be sung
114 
115 我有太多歌曲永远不会被唱起
116 
117 I feel the bitter taste of tears upon my tongue
118 
119 我尝到了舌尖泪水的苦涩滋味
120 
121 The time has come for me to pay for yesterday
122 
123 终于到了付出代价的时间 为了昨日
124 
125 When I was young
126 
127 当我年少轻狂
View Code

 

同时打开多个文件的写法

 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 sung
102 
103 有那么那么多甜美的曲儿等我歌唱
104 
105 So many wild pleasures lay in store for me
106 
107 有那么多肆意的快乐等我享受
108 
109 And so much pain my eyes refused to see
110 
111 还有那么多痛苦 我的双眼却视而不见
112 
113 There are so many songs in me that won't be sung
114 
115 我有太多歌曲永远不会被唱起
116 
117 I feel the bitter taste of tears upon my tongue
118 
119 我尝到了舌尖泪水的苦涩滋味
120 
121 The time has come for me to pay for yesterday
122 
123 终于到了付出代价的时间 为了昨日
124 
125 When I was young
126 
127 当我年少轻狂
View Code

 



一、读取大文件的最后一行内容(例如:查看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             break
11         offs *= 2    #相当于两倍文件的内容中查找

执行结果:

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

 

 


 

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

1、写文件

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

执行结果:

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

1 abc
2 adfdsssfsf
3 adfdssfdf

 

2、读文件

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

执行结果:

1 abc
2 adfdsssfsf
3 adfdssfdf

 

3、readlines 读成一个列表

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

执行结果:

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

 

4、readline 一次读取一行

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

执行结果:

1 abc

 

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

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

执行结果:

1 abc
2 
3 adfdsssfsf
4 
5 adfdssfdf

 

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

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

执行结果:

1 abc
2 adfdsssfsf
3 adfdssfdf

 

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

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

执行结果:

1 abc
2 adfdsssfsf
3 adfdssfdf

 

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

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

执行结果:

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

 

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

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

执行结果:

1 abc
2 adfdsssfsf
3 adfdssfdf

 

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

a.txt文件内容

1 abc
2 adfdsssfsf
3 adfdssfdf

代码:

 1 import os
 2 fr = open('a.txt','r',encoding='utf-8')
 3 fw = open('b.txt','w',encoding='utf-8')
 4 
 5 for i in fr:
 6     if 'a' in i:
 7         y = i.replace('a','0')
 8     fw.write(y)
 9 
10 fr.close()
11 fw.close()
12 
13 os.rename('a.txt','a.bak')  #先把a.txt备份
14 os.rename('b.txt','a.txt')   #再把b.txt重命名为a.txt
15 os.remove('a.bak')           #再删除备份的a.bak

执行结果:

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

 

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

a.txt里面的内容

1 abc
2 adfdsssfsf
3 adfdssfdf

 

b.txt里面的内容

1 abc
2 adfdsssfsf
3 adfdssfdf

代码:

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

执行结果:

b.txt文件内容

1 0bc          #a替换成0
2 0dfd555f5f   #s替换成5
3 0dfd55fdf

 

12、r+ 先读再写 (

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

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

1 abc
2 adfd555f5f
3 adfd55fdf

代码:

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

执行结果:

1 #先读出列表
2 
3 ['abc\n', 'adfdsssfsf\n', 'adfdssfdf\n']

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

1 6bc
2 6dfdsssfsf
3 6dfdssfdf

 

13、字符串转成二进制

方法一:

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

执行结果:

1 b'12345gdfafdsa'

 

方法二:

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

执行结果:

1 b'fsdfdsfssdsfds'

 

posted @ 2016-12-06 10:00  努力哥  阅读(5085)  评论(1编辑  收藏  举报