一、打开文件、读、写
1 """ 2 打开方式 3 a = append 追加 4 w = 写文件 5 r = 只读 6 r+ = 读+追加 # 打开老文件 7 w+ = 追加+读 # 创建新文件,用处不大 8 rb = 读二进制文件 9 wb = 写二进制文件 # f.write('hello binary\n'.encode() )10 rU或r+U = 在读取时可以将\r\n自动转换成\n 11 """12 13 # 打开文件,赋值给文件句柄14 f = open('yesterday', 'w', encoding='utf-8')15 with open('yesterday', 'r', encoding='utd-8') as f: # 自动关闭16 f.read()17 18 # 读文件19 print(f.read(5)) # 读前50个字符20 print(f.readline()) # 读一行21 f.readable() # 判断文件是否可读22 23 # 写文件24 f.write('1,\n')25 f.write('2')26 f.writable() # 判断文件是否可写27 28 # 返回文件句柄所在位置29 print(f.tell())30 # 更改文件句柄所在位置31 f.seek(0)32 # 判断文件句柄是否可移动33 f.seekable()34 35 # 返回文件编码36 print(f.encoding)37 38 # 返回文件名39 print(f.name)40 41 # 将write的内容实时刷新到硬盘上42 print(f.flush())43 print(f.buffer)44 45 # 关闭文件46 f.close()47 f.clised() # 判断文件是否关闭48 49 # 保留文件前10个字符,其余内容删除50 f.truncate(10) # 文件打开方式应该使用'a'
二、修改文件内容并储存为新文件
1 f = open('yesterday', 'r', encoding='utf-8') 2 f_new = open('yesterday.new', 'w', encoding='utf-8') 3 4 for line in f: 5 if '有那么多肆意的快乐等我享受' in line: 6 line = line.replace('我', 'Alex', 1) 7 f_new.write(line) 8 9 f.close()10 f_new.close()
附:yueterday文件内容
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有那么多肆意的快乐等Alex享受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有那么多肆意的快乐等Alex享受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当我年少轻狂