文件操作

对文件操作流程

  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("yestday",'r',encoding="utf-8") #定义文件句柄(定义这个文件的内存对象,包括文件的文件名,字符集,大小,和文件在硬盘上的位置)
data = f.read() #读取文件,只能读不能写入

f = open("yestday1",'w',encoding="utf-8")#以写的形式打开文件,不能读取文件
data = f.write("我爱北京天安门\n") #把内容写入不到文件,如果文件之前有内容,会被覆盖
data = f.write("天安门上太阳升")

f = open("yestday1",'a',encoding="utf-8")#以追加的方式打开文件,原来的内容不会被覆盖,仍然不能读取文件
data = f.write("\n太阳升升升。。。。。")

循环

f = open("yestday",'r',encoding="utf-8")
#利用循环打印前5行
for i in range(5):
    print(f.readline())

f = open("yestday",'r',encoding="utf-8")
#f.readlines把文件内容转换成列表,每行一个元素
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']

print(f.readlines()[0:5]) #打印元素的前5行

['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']

f = open("yestday",'r',encoding="utf-8")
#利用循环打印文件列表,如果列表元素是以\n结尾,打印出来的内容会换行
for line in f.readlines():
    print(line)

There are so many songs in me that won't be sung

我有太多歌曲永远不会被唱起

I feel the bitter taste of tears upon my tongue

我尝到了舌尖泪水的苦涩滋味

for line in f.readlines():
    print(line.strip()) #去掉换行

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young

f = open("yestday",'r',encoding="utf-8")
#利用index找出列表下标,并打印出前10行,不适合大文件
for index,line in enumerate(f.readlines()):
    if index ==9:
        break
    print(index,line.strip())

0 Somehow, it seems the love I knew was always the most destructive kind
1 不知为何,我经历的爱情总是最具毁灭性的的那种
2 Yesterday when I was young
3 昨日当我年少轻狂
4 The taste of life was sweet
5 生命的滋味是甜的
6 As rain upon my tongue
7 就如舌尖上的雨露
8 I teased at life as if it were a foolish game
9 我戏弄生命 视其为愚蠢的游戏

f = open("yestday",'r',encoding="utf-8")
#不转换文件内容格式,利用计数器实现打印文件前10行
count = 0
for line in f:
    print(line.strip())
    if count == 9:
      break
    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
我戏弄生命 视其为愚蠢的游戏

 基本语法

f = open("yestday",'r',encoding="utf-8")
print(f.encoding) #打印文件字符编码
print(f.fileno()) #返回文件句柄在内存中的编号
print(f.name) #打印文件名字
print(f.readable()) #判断文件是否可读
print(f.seekable()) #判断光标是否能移动

f.truncate(20) #从第一个字符开始,截断至第20个字符,括号里不写内容默认会把内容清空
f = open("yestday",'r+',encoding="utf-8") #以读写方式打印文件内容,新内容会被追加到最后
f = open("yestday",'a+',encoding="utf-8") #以追加写读方式打印文件内容
f = open("yestday",'w+',encoding="utf-8") #以写读方式打印文件内容,先写,如果文件有内容会被覆盖
f = open("yestday",'rb') #以二进制方式打读取文件内容
f = open("yestday",'wb')#以二进制方式写入文件内容
f.write("hello-----\n".encode()) #把内容转换成2进制

#打印进度条
import sys,time

for i in range(20):
    sys.stdout.write("#") #stdout标准输出打印20个#
    sys.stdout.flush() #不要缓存,直接显示
    time.sleep(0.5) #每0.5秒打印一个

 文件修改

f = open("yestday",'r',encoding="utf-8") #定义旧文件
f_new = open("yestday_new",'w',encoding="utf-8") #定义新文件
#按照行循环旧文件,当出现需要修改的内容时,把新的内容替换到行里,
    # 最后把所有的内容重新输入到新文件中
for line in f: 
    if "生命的滋味是甜的" in line :
        line = line.replace("生命的滋味是甜的","生命的滋味是甜的我怎么不知道")
    f_new.write(line)
f.close()
f_new.close()
#根据外部参数来实现替换文件中的内容
import sys
f = open("yestday",'r',encoding="utf-8") #定义旧文件
f_new = open("yestday_new",'w',encoding="utf-8") #定义新文件
#按照行循环旧文件,当出现需要修改的内容时,把新的内容替换到行里,
# 最后把所有的内容重新输入到新文件中
find_str = sys.argv[1] #定义执行脚本输入的第一个参数
replace_str = sys.argv[2] #定义执行脚本输入的第二个参数

for line in f:
if find_str in line :
line = line.replace(find_str,replace_str) #把第一个参数的内容替换成第二个参数的内容
f_new.write(line)
f.close()
f_new.close()
 

 with语句

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

with open('log','r') as f:
     
    ...
#如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

#在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:
    pass

 

posted @ 2017-06-25 19:55  七天&七天  阅读(199)  评论(0编辑  收藏  举报