python基础-文件操作

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 #读取文件内容,并打印出来
2 data = open("yesterday",encoding="utf-8").read()
3 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 #data = open("yesterday",encoding="utf-8").read()
 2 #打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
 3 f = open("yesterday",encoding="utf-8")  #文件句柄(文件内存对像。包含 (文件名,字符集,大小,硬盘的起启位置))
 4 data = f.read()
 5 data2 = f.read()
 6 print(data)
 7 print('--------------data2---------------',data2)

结果:

只输出data1的结果

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

 


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

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

r   :读

w  :写

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

内容如下:

5 #读文件或打开文件
6 #data = open("yesterday",encoding="utf-8").read()
7 f = open("yesterday",encoding="utf-8")   #文件句柄
8 data = f.read()
9 print(data)

执行结果:

 View Code

write创建一个文件名为:
yesterday2的新文件,并可以写入内容
1 f = open("yesterday2",'w',encoding="utf-8")   #文件句柄
2 f.write("我爱北京天安门,\n")    # write创建一个新文件,并可以写入内容
3 f.write("天安门前太阳升")

执行结果:

yesterday2.txt

1 我爱北京天安门,
2 天安门前太阳升

 


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

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

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

  • rU
  • r+U

 

 

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

 1 f = open("yesterday2",'r+',encoding="utf-8")  #文件句柄 ,读写
 2 print(f.readline())
 3 print(f.readline())
 4 print(f.readline())
 5 print(f.tell())    #打印光标
 6 f.write("------------------diao-------------------")

7 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文件中的内容

 View Code

 

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

示例1:

 1 #f = open("yesterday2",'r+',encoding="utf-8")  #文件句柄
 2 f = open("yesterday2",'w+',encoding="utf-8")  #文件句柄
 3 print(f.readline())
 4 print(f.readline())
 5 print(f.readline())
 6 print(f.tell())    #打印光标
 7 f.write("------------------diao-------------------")
 8 print(f.readline())

执行结果:

往yesterday2文件中写入内容

1 ------------------diao-------------------

 

示例2:

 1
 2 #f = open("yesterday2",'r+',encoding="utf-8")  #文件句柄
 3 f = open("yesterday2",'w+',encoding="utf-8")  #文件句柄
 4 
 5 #创建文件写4行
 6 f.write("------------------diao------------------1\n")
 7 f.write("------------------diao------------------1\n")
 8 f.write("------------------diao------------------1\n")
 9 f.write("------------------diao------------------1\n")
10 
11 #打印位置
12 print(f.tell())
13
14 #返回指针到第10行
15 f.seek(10)
16 
17 #打印出来
18 print(f.readline())
19 
20 #写入下面这句话
21 f.write("should be at the begining of the second line")
22 
23 #关闭
24 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 #f = open("yesterday2",'r+',encoding="utf-8")  #文件句柄  读写
2 #f = open("yesterday2",'w+',encoding="utf-8")  #文件句柄  写读
3 f = open("yesterday2",'a+',encoding="utf-8")  #文件句柄  追加读写
4 #创建文件写4行
5 f.write("------------------diao------------------1\n")
6 f.write("------------------diao------------------1\n")
7 f.write("------------------diao------------------1\n")
8 f.write("------------------diao------------------1\n")
9 #打印位置
10print(f.tell())
11 #返回指针到第10行
12 f.seek(10)
13 #打印出来
14 print(f.readline())
15 #写入下面这句话
16 f.write("should be at the begining of the second line")
17 #关闭
18 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 f = open("yesterday2",'rb')  #文件句柄  二进制文件
2 print(f.readline())
3 print(f.readline())
5 print(f.readline())

执行结果:

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

 

文件操作的二进制读写

1 f = open("yesterday2",'wb')  #文件句柄  二进制文件
2 f.write("hello binary\n".encode())
3 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 #先读取,再写入一行
 2 f = open("yesterday2",'r',encoding="utf-8")
 3 f_new = open("yesterday2.bak",'w',encoding="utf-8")
 4 
 5 for line in f:
 6     if "肆意的快乐等我享受" in line:
 7         line =line.replace("肆意的快乐等我享受","肆意的快乐等Alex享受")
 8     f_new.write(line)
 9 f.close()
10 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 import sys
 2 #先读取,再写入一行
 3 f = open("yesterday2",'r',encoding="utf-8")
 4 f_new = open("yesterday2.bak",'w',encoding="utf-8")
 5 
 6 find_str = sys.argv[1]
 7 replace_str = sys.argv[2]
8 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文件内容

 View Code

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

 1 import sys
 2 #先读取,再写入一行
 3 # f = open("yesterday2",'r',encoding="utf-8")
 4 
 5 with open("yesterday2",'r',encoding="utf-8") as f:
 6     for line in f:
 7        print(line)

执行结果:

 View Code

 

同时打开多个文件的写法

1 import sys
2 #先读取,再写入一行
3# f = open("yesterday2",'r',encoding="utf-8")
4 
5 with open("yesterday2",'r',encoding="utf-8") as f ,\
6         open("yesterday2", 'r', encoding="utf-8") as f2:
7    for line in f:
8         print(line)

执行结果:

 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 @ 2017-04-24 15:12  karina梅梅  阅读(252)  评论(0编辑  收藏  举报