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

扫描二维码关注公众号,回复: 1487583 查看本文章

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('Lry') #打开文件
first_line=f.readline()
print('first line',first_line)
print('我是分割线'.center(50,'-'))
data=f.read() #读取剩下所有内容,文件大时不要用
print(data)  #打印文件
f.close() #关闭文件

  

打开文件的模式有:

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

读文件示例

法1:

1、先创建一个文件名称为:Lry 文本文件

2.  读取文件

#读取文件内容,并且打印
#!/usr/bin/env python 
#  -*- coding:utf-8 -*-
#Author: Christian
data=open('Lry',encoding='utf8').read()
print(data) 

法2:

打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
(只能读取一次,data1没有被读出)
f = open('Lry',encoding ='utf8')   #打开的文件内存对像,给他赋一个变量,再去读取这个变量,找到这个值
data=f.read()
data1=f.read()
print(data)
print('------我是分割线------'.center(70,'-'),data1)

 结果:只能读出data的数据,不能读出data1的数据 


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

这种方法有个特性:要么只读,要么只写。不能同时读又写.同时会清空文件中的内容。特别危险。

r   :读

w  :写

f = open("Lry",'w',encoding="utf-8")   #文件句柄
print(f.read())
f.write('看看效果了')

 执行结果:报错,同时清空了原Lry中的内容

Traceback (most recent call last):
  File "F:/复习/文件处理.py", line 27, in <module>
    print(f.read())
io.UnsupportedOperation: not readable

   

往文件中写入内容

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

 同级目录下创建名为yesterday的文本。

在原文件的基础上进行追加

a相当于append

f = open("Lry",'a',encoding="utf-8")   #文件句柄
f.write('这个世界会好吗\n')
f.write('应该会吧')

 注意:用了a追加的方法后,在使用.read()方法就会报错

f = open("Lry",'a',encoding="utf-8")   #文件句柄
f.write('这个世界会好吗\n')
f.write('应该会吧')
f.read()

  

Traceback (most recent call last):
  File "F:/复习/文件处理.py", line 34, in <module>
    f.read()
io.UnsupportedOperation: not readable

  所以,只能追加不能再去读取!

读取文件的前N行数据
1.
读取几行,就用几次.readline()
f=open('Lry','r',encoding='utf8')
print(f.readline())
print(f.readline())
print(f.readline()) #读取几行,就f.readline()几次

  执行结果

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

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

Yesterday when I was young

 2.采用for循环方式

f=open('Lry','r',encoding='utf8')
# print(f.readline())
# print(f.readline())
# print(f.readline())   #读取几行,就f.readline()几次

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

  

打印文件所有内容

1.直接打印.read()

f=open('Lry','r',encoding='utf8')
print(f.read())

  执行结果是和原文件的格式一样,中间不插入空格

2.使用.readlines() 

f=open('Lry','r',encoding='utf8')
print(f.readlines())

  执行结果

['Somehow, it seems the love I knew was always the most destructive kind\n', '不知为何,我经历的爱情总是最具毁灭性的的那种\n', 'Yesterday when I was young\n', '昨日当我年少轻狂\n', 'The taste of life was sweet\n', '生命的滋味是甜的\n', 'As rain upon my tongue\n', '就如舌尖上的雨露\n', 'I teased at life as if it were a foolish game\n', '我戏弄生命 视其为愚蠢的游戏\n', 'The way the evening breeze\n', '就如夜晚的微风\n', 'May tease the candle flame\n', '逗弄蜡烛的火苗\n', 'The thousand dreams I dreamed\n', '我曾千万次梦见\n', 'The splendid things I planned\n', '那些我计划的绚丽蓝图\n', 'I always built to last on weak and shifting sand\n', '但我总是将之建筑在易逝的流沙上\n', 'I lived by night and shunned the naked light of day\n', '我夜夜笙歌 逃避白昼赤裸的阳光\n', 'And only now I see how the time ran away\n', '事到如今我才看清岁月是如何匆匆流逝\n', 'Yesterday when I was young\n', '昨日当我年少轻狂\n', 'So many lovely songs were waiting to be sung\n', '有那么多甜美的曲儿等我歌唱\n', 'So many wild pleasures lay in store for me\n', '有那么多肆意的快乐等我享受\n', 'And so much pain my eyes refused to see\n', '还有那么多痛苦 我的双眼却视而不见\n', 'I ran so fast that time and youth at last ran out\n', '我飞快地奔走 最终时光与青春消逝殆尽\n', 'I never stopped to think what life was all about\n', '我从未停下脚步去思考生命的意义\n', 'And every conversation that I can now recall\n', '如今回想起的所有对话\n', 'Concerned itself with me and nothing else at all\n', '除了和我相关的 什么都记不得了\n', 'The game of love I played with arrogance and pride\n', '我用自负和傲慢玩着爱情的游戏\n', 'And every flame I lit too quickly, quickly died\n', '所有我点燃的火焰都熄灭得太快\n', 'The friends I made all somehow seemed to slip away\n', '所有我交的朋友似乎都不知不觉地离开了\n', "And only now I'm left alone to end the play, yeah\n", '只剩我一个人在台上来结束这场闹剧\n', 'Oh, yesterday when I was young\n', '噢 昨日当我年少轻狂\n', 'So many, many songs were waiting to be sung\n', '有那么那么多甜美的曲儿等我歌唱\n', 'So many wild pleasures lay in store for me\n', '有那么多肆意的快乐等我享受\n', 'And so much pain my eyes refused to see\n', '还有那么多痛苦 我的双眼却视而不见\n', "There are so many songs in me that won't be sung\n", '我有太多歌曲永远不会被唱起\n', 'I feel the bitter taste of tears upon my tongue\n', '我尝到了舌尖泪水的苦涩滋味\n', 'The time has come for me to pay for yesterday\n', '终于到了付出代价的时间 为了昨日\n', 'When I was young\n', '当我年少轻狂']

  发现结果是一个列表,而且每一句后面有\n转义字符,那么我们可以想到用for循环将其遍历

f=open('Lry','r',encoding='utf8')
for i in f.readlines():
    print(i)

  执行结果:

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

当我年少轻狂

  发现是不管是打印N行或者是全部打印出来,发现都带有换行和空格,

  此时我们可以用.strip()方法

f=open('Lry','r',encoding='utf8')
for i in f.readlines():
    print(i.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行示例

 法1:不推荐使用,效率太低
f=open('Lry','r',encoding='utf8')
for idex,line in enumerate(f.readlines()):
    if idex == 9:
        print('我是分割线'.center(50,'_'))
        continue
    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
当我年少轻狂

  

法2:推荐使用,效率高

f=open('Lry','r',encoding='utf8')
count=0
for line in f:
    if count ==9:
        print('我是分割线'.center(50,'_'))
        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
______________________我是分割线_______________________
我戏弄生命 视其为愚蠢的游戏
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
当我年少轻狂

  



seek()和tell() 

seek():移动文件读取指针到指定位置
tell():返回文件读取指针的位置,即当前位置

print(f.tell())  #0
print(f.readline(5))   #f.readline()是按字符进行读取的
print(f.tell())  #5
print(f.readline())  #ow, it seems the love I knew was always the most destructive kind
print(f.tell())   #72

#回到第几个字符,想回第几个字符,就输入数字几
seek(10)
print(f.readline()) #t seems the love I knew was always the most destructive kind
 

  执行结果

0
Someh
5
ow, it seems the love I knew was always the most destructive kind

72
t seems the love I knew was always the most destructive kind

  

encoding 打印文件编码

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

name  打印文件名称

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

f=open('Lry','r',encoding='utf8')
print(f.encoding)   #打印文件编码
print(f.name)    #打印文件名字
print(f.fileno())   #返回文件句柄,在内存中的编号
print(f.isatty())  # #打印一个终端设备(用于打印机交互)

  

执行结果

utf8
Lry
3
False

  

seekable  移动指针位置

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

f=open('Lry','r',encoding='utf8')
print(f.seekable())  
True

 查看buffer(本身buffer,也是内存中的临时文件)

f=open('Lry','r',encoding='utf8')
print(dic(f.buffer))

  执行结果

['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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了一下,才会保存到硬盘中去。

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

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

 



在屏幕上打印进度条

  首先想到用print()打印符号,发现每次打印后默认换行,后面加end=''又发现新问题,符号会同时打印出来,没有达到预期效果。

  法1:借助sys.stdout.write()    (不理想)

import sys
a=sys.stdout.write('x')   #标准输出到屏幕
print(a)

  法2:(完美解决) 

import sys,time
for i in range(50):
    sys.stdout.write('*')
    sys.stdout.flush()
    time.sleep(0.1)

  


  

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

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

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

  • rU
  • r+U

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

f=open('Lry','r+',encoding='utf8')
for i in range(5):
    print(f.readline().strip())
print(f.tell())  #打印光标位置
f.write('陈粒的歌听的很少')

 执行结果

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
238

  

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

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(0)

#打印出来
print(f.read())

#写入下面这句话
f.write("should be at the begining of the second line")

  执行结果

172
------------------diao------------------1
------------------diao------------------1
------------------diao------------------1
------------------diao------------------1

  

   a+,同a,追加读写 

f = open("yesterday3",'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(0)
#打印出来
print(f.readline())
#写入下面这句话
f.write("should be at the begining of the second line")
#关闭
f.close()

  


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

  • rb
  • wb
  • ab

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

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'

  

文件操作的二进制读写

f = open("yesterday2",'wb')  #文件句柄  二进制文件
f.write("hello binary\n".encode())
f.close()

  



   更改文件内容

  1.打开一个原文件,进行读取

  2.将读取到的内容写入一个新的文件,并进行修改

这么多年你一个人一直在走
方向和天气的节奏会让你忧愁
你说你遇见了一大堆奇怪的人 
他们看上去好像都比你开心 [1]
你能不能抽空替我去一个地方
据说那的人都擅长给别人答案
如果你想知道关于它的其他事情
我也不会给你刘堃的电话号码 [1]
多想和你一样臭不要脸
墨镜和表情都挂在脸上
穿什么吃什么玩什么都可以
今天爱他明天恨他也可以 [1]
这么多年我一个人一直在走
走过了人性的背后和白云苍狗
总以为答案会出现在下一个车站
随后的事情我不说你也能明白 [1]
悲伤是奢侈品我消受不起
快乐像噩梦总让人惊醒
你要哭吧就哭吧就随意吧
反正我早已习惯不去相信 [1]
悲伤是奢侈品我消受不起
快乐像噩梦一转眼惊醒
你要走吧就走吧就随意吧
反正我早已决定不再回去 [1]

  

f=open('dingxi','r',encoding='utf8')
new_f=open('dingxi2','w',encoding='utf8')
for line in f:
    if '多想和你一样臭不要脸' in line:
        line = line.replace('多想和你一样臭不要脸','就是这么的臭不要脸')
    new_f.write(line)
f.close()
new_f.close()

 执行结果:创建一个新的文件,并且替换原来的‘多想和你一样臭不要脸’

这么多年你一个人一直在走
方向和天气的节奏会让你忧愁
你说你遇见了一大堆奇怪的人 
他们看上去好像都比你开心 [1]
你能不能抽空替我去一个地方
据说那的人都擅长给别人答案
如果你想知道关于它的其他事情
我也不会给你刘堃的电话号码 [1]
就是这么的臭不要脸
墨镜和表情都挂在脸上
穿什么吃什么玩什么都可以
今天爱他明天恨他也可以 [1]
这么多年我一个人一直在走
走过了人性的背后和白云苍狗
总以为答案会出现在下一个车站
随后的事情我不说你也能明白 [1]
悲伤是奢侈品我消受不起
快乐像噩梦总让人惊醒
你要哭吧就哭吧就随意吧
反正我早已习惯不去相信 [1]
悲伤是奢侈品我消受不起
快乐像噩梦一转眼惊醒
你要走吧就走吧就随意吧
反正我早已决定不再回去 [1]

  

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

  (有待研究sys.argv)

import sys
f=open('dingxi','r',encoding='utf8')
new_f=open('dingxi3','w',encoding='utf8')
for line in f:
    find_str = sys.argv[1]
    replace_str = sys.argv[2]
    if find_str in line:
        line = line.replace(find_str,replace_str)
    new_f.write(line)
f.close()
new_f.close()

  

 



 

with语句

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

with open('dingxi','r',encoding='utf8') as f:
    ……

  

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

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

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

  

同时打开两个文件的操作

with open('dingxi','r',encoding='utf8') as f,open('Lry','r',encoding='utf8') as f1:
    print(f.readline())
    print(f1.readline())

  执行结果:

这么多年你一个人一直在走

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

 


读取大文件的最后一行内容(例如:查看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('rizhi','rb')
for i in f:
    offs=-10
    while 1:
        f.seek(offs,2)   #offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
        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('dingxi','rb')
print(f.read())

  执行结果

b'\xe8\xbf\x99\xe4\xb9\x88\xe5\xa4\x9a\xe5\xb9\xb4\xe4\xbd\xa0\xe4\xb8\x80\xe4\xb8\xaa\xe4\xba\xba\xe4\xb8\x80\xe7\x9b\xb4\xe5\x9c\xa8\xe8\xb5\xb0\r\n\xe6\x96\xb9\xe5\x90\x91\xe5\x92\x8c\xe5\xa4\xa9\xe6\xb0\x94\xe7\x9a\x84\xe8\x8a\x82\xe5\xa5\x8f\xe4\xbc\x9a\xe8\xae\xa9\xe4\xbd\xa0\xe5\xbf\xa7\xe6\x84\x81\r\n\xe4\xbd\xa0\xe8\xaf\xb4\xe4\xbd\xa0\xe9\x81\x87\xe8\xa7\x81\xe4\xba\x86\xe4\xb8\x80\xe5\xa4\xa7\xe5\xa0\x86\xe5\xa5\x87\xe6\x80\xaa\xe7\x9a\x84\xe4\xba\xba\xe3\x80\x80\r\n\xe4\xbb\x96\xe4\xbb\xac\xe7\x9c\x8b\xe4\xb8\x8a\xe5\x8e\xbb\xe5\xa5\xbd\xe5\x83\x8f\xe9\x83\xbd\xe6\xaf\x94\xe4\xbd\xa0\xe5\xbc\x80\xe5\xbf\x83 [1]\r\n\xe4\xbd\xa0\xe8\x83\xbd\xe4\xb8\x8d\xe8\x83\xbd\xe6\x8a\xbd\xe7\xa9\xba\xe6\x9b\xbf\xe6\x88\x91\xe5\x8e\xbb\xe4\xb8\x80\xe4\xb8\xaa\xe5\x9c\xb0\xe6\x96\xb9\r\n\xe6\x8d\xae\xe8\xaf\xb4\xe9\x82\xa3\xe7\x9a\x84\xe4\xba\xba\xe9\x83\xbd\xe6\x93\x85\xe9\x95\xbf\xe7\xbb\x99\xe5\x88\xab\xe4\xba\xba\xe7\xad\x94\xe6\xa1\x88\r\n\xe5\xa6\x82\xe6\x9e\x9c\xe4\xbd\xa0\xe6\x83\xb3\xe7\x9f\xa5\xe9\x81\x93\xe5\x85\xb3\xe4\xba\x8e\xe5\xae\x83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\x8a\xe9\x86\x92\r\n\xe4\xbd\xa0\xe8\xa6\x81\xe8\xb5\xb0\xe5\x90\xa7\xe5\xb0\xb1\xe8\xb5\xb0\xe5\x90\xa7\xe5\xb0\xb1\xe9\x9a\x8f\xe6\x84\x8f\xe5\x90\xa7\r\n\xe5\x8f\x8d\xe6\xad\xa3\xe6\x88\x91\xe6\x97\xa9\xe5\xb7\xb2\xe5\x86\xb3\xe5\xae\x9a\xe4\xb8\x8d\xe5\x86\x8d\xe5\x9b\x9e\xe5\x8e\xbb [1]'

 decode编码出结果

f=open('dingxi','rb')
data=f.read()
data=data.decode('utf8')
print(data)

 执行结果

这么多年你一个人一直在走
方向和天气的节奏会让你忧愁
你说你遇见了一大堆奇怪的人 
他们看上去好像都比你开心 [1]
你能不能抽空替我去一个地方
据说那的人都擅长给别人答案
如果你想知道关于它的其他事情
我也不会给你刘堃的电话号码 [1]
多想和你一样臭不要脸
墨镜和表情都挂在脸上
穿什么吃什么玩什么都可以
今天爱他明天恨他也可以 [1]
这么多年我一个人一直在走
走过了人性的背后和白云苍狗
总以为答案会出现在下一个车站
随后的事情我不说你也能明白 [1]
悲伤是奢侈品我消受不起
快乐像噩梦总让人惊醒
你要哭吧就哭吧就随意吧
反正我早已习惯不去相信 [1]
悲伤是奢侈品我消受不起
快乐像噩梦一转眼惊醒
你要走吧就走吧就随意吧
反正我早已决定不再回去 [1]

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

  a.txt文件内容 

abc
adafhjkklhfg
adaaaagafklakh;fkl

  

import os
fr=open('a','r',encoding='utf8')
fw=open('b','w',encoding='utf8')
for i in fr:
    if 'a' in i:
        y=i.replace('a','0')
    fw.write(y)

fr.close()
fw.close()

os.rename('a','a.bak')  #先将a备份
os.rename('b','a')  #再将b重命名为a
os.remove('a.bak')#最后将a.bak移除

  执行结果

0bc
0d0fhjkklhfg
0d0000g0fkl0kh;fkl

  

 将字符串转换为二进制数

 1.

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

  执行结果

b'12345gdfafdsa'

  2.

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

  执行结果

b'fsdfdsfssdsfds'

  

r+ 先读再写 

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

1 abc
2 adfd555f5f
3 adfd55fdf

  

with open('a',"r+",encoding='utf8') as f:
    a=f.readlines()
    print(a)
    f.seek(0)
    for i in f:
        if 'a' in i:
            y=i.replace('a','6')
            f.write(y)

  




 

 

猜你喜欢

转载自www.cnblogs.com/huiyichanmian/p/9143025.html