python基础1-文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件 

现有文件yesterday如下

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

  

打开文件的模式有:

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

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

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

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

  • rU
  • r+U

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

  • rb
  • wb
  • ab

操作如下:

#在2.x中有file函数,在3.x中只有open
data = open('yesterday',encoding='utf-8').read()  #必须指定字符编码
print(data)

f = open('yesterday','r',encoding='utf-8')      #文件句柄(文件的内存对象)
data = f.read()

print(data)

#写就创建文件
f = open('yesterday2','w',encoding='utf-8')
f.write('你是谁\n')
f.write('你猜呢')

f = open('yesterday2','a',encoding='utf-8')
f.write('\n我不猜')
f.close()


#readline()   读一行
f = open('yesterday','r',encoding='utf-8')
# print(f.readline())

for i in range(5):
    print(f.readline())

f = open('yesterday','r',encoding='utf-8')

#每行为一个元素,成为一个列表,文件大会撑爆内存
print(f.readlines())

f = open('yesterday','r',encoding='utf-8')
for line in f.readlines():
    print(line.strip())

#对其中某行做处理,文件大不宜
f = open('yesterday','r',encoding='utf-8')
for index,line in enumerate(f.readlines()):

    if index == 9 :
        print('我是分割线'.center(50,'-'))
        continue
    print(line.strip())

#内存中只保留一行,适合常用,f变为啦一个迭代器
f = open('yesterday','r',encoding='utf-8')
count = 0
for line in f :
    if count == 9 :
        print('我是分割线'.center(50,'-'))
        count += 1
        continue
    print(line.strip())
    count +=1


f = open('yesterday','r',encoding='utf-8')

#打印光标位置
print(f.tell())
print(len(f.readline()))
print(f.tell())

#移动光标,按字符位置算,
f.seek(0)
print(f.readline())

f = open('yesterday','r',encoding='utf-8')

#打印光标位置
print(f.tell())
print(len(f.readline()))
print(f.tell())

#移动光标,按字符位置算,
f.seek(10)
print(f.tell())
print(f.readline())       #从当前位置到第一个换行符



f = open('yesterday','r',encoding='utf-8')

#f.detach()  编辑一半,可以中途改变字符编码
#print(f.encoding)      #打印字符编码
#print(f.fileno())         #返回一个所打开文件的编号,不用
#print(f.name)          #打印文件名
#print(f.isatty())        #是否是一个终端设备文件

#print(f.seekable())      #光标能否移动
#print(f.readable())       #文件是否可读
#print(f.writable())       #文件是否可写

print(dir(f.buffer))


f = open('yesterday2','w',encoding='utf-8')
#将文件从内存中刷到硬盘上,演示需要cmd下,注

f.write('wo shi shui \n')
f.write('wo dao di shi shui\n')
f.flush()

进度条动态显示,缓存flush作用
import sys,time

for i in range(50):
    sys.stdout.write('#')
    sys.stdout.flush()
    time.sleep(0.5)


#判断文件是否关闭,返回True或False
f = open('yesterday2','w',encoding='utf-8')
f.close()
print(f.closed)

f = open('yesterday2','a',encoding='utf-8')
f.seek(10)
#截断,从头开始,上面移动光标也不好使
f.truncate(20)

#读写

f = open('yesterday2','r+',encoding='utf-8')

print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(10)
print(f.tell())
f.write('\ndiao')
#就是写不到指定光标后面,只能写到文件后面


#写读,没什么用
f = open('yesterday2','w+',encoding='utf-8')

f.write('11111111111')
f.write('22222222222')
f.write('33333333333')
print(f.tell())
f.seek(10)
print(f.tell())
print(f.readline())
f.write('diao')
#就是写不到指定光标后面,只能写到文件后面


#追加读
f = open('yesterday2','a+',encoding='utf-8')

f.write('11111111111')
f.write('22222222222')
f.write('33333333333')
print(f.tell())
f.seek(10)
print(f.tell())
print(f.readline())
f.write('diao')

#rb,wb,ab   二进制文件,如视频

f = open('yesterday2','rb')
print(f.readline())

#wb
f = open('yesterday2','wb')
f.write('hello binary\n'.encode('utf-8'))    #因为是二进制,所以必须编码

'''

f = open('yesterday2','r',encoding='utf-8')
f_new = open('yesterday2.bak','w',encoding='utf-8')
for line in f:
    if  '有那么多肆意的快乐等我享受' in line:
        line = line.replace('有那么多肆意的快乐等我享受','有那么多肆意的快乐等且听风吟92享受')
    #     f_new.write(line)
    # else:
    #     f_new.write(line)
    f_new.write(line)
f.close()
f_new.close()

  

posted @ 2017-04-03 18:22  larlly  阅读(109)  评论(0)    收藏  举报