Python 文件操作
一、Python文件I/O
打印到屏幕
>>> print("Python 是一个非常棒的语言,不是吗?") Python 是一个非常棒的语言,不是吗? >>> >>> import sys >>> sys.stdout.write("Python 是一个非常棒的语言,不是吗?") Python 是一个非常棒的语言,不是吗?21 >>>
读取键盘输入
>>> str = input('please input something here: ') # python3.x 相当于Python2.x的raw_input() please input something here: something >>> print('the content you put is : ', str) the content you put is : something >>>
打开和关闭文件
open 函数
你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。
语法:
file object = open(file_name [, access_mode][, buffering])
各个参数的细节如下:
- file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
- access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
- buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
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 当我年少轻狂
#!/usr/bin/evn python # -*- coding:utf-8 -*- # Author: antcolonies # data = open('yesterday1.lrc') # 默认为系统的编码格式 # UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 106: illegal multibyte sequence # data = open('yesterday1.lrc',encoding='utf-8') # data: <_io.TextIOWrapper name='yesterday1.lrc' mode='r' encoding='utf-8'> f = open('yesterday1.lrc',encoding='utf-8') # 内存对象f,在文件操作中称为句柄 print(f) # f: <_io.TextIOWrapper name='yesterday1.lrc' mode='r' encoding='utf-8'> # 默认打开的模式为'读' data = f.read() # 读取整个文件 data2 = f.read() print(id(data),id(data2)) # 42019856 6715464 f.write('Love u') # io.UnsupportedOperation: not writable f = open('yesterday2.lrc','w',encoding='utf-8') # print(f) <_io.TextIOWrapper name='yesterday2.lrc' mode='w' encoding='utf-8'> # 'w'模式下打开会创建一个yesterday2.lrc名称的文件,若文件存在,则覆盖原文件 data = f.read() # io.UnsupportedOperation: not readable f.write('Love u ') f.write('Hate u') f = open('yesterday2.lrc','a',encoding='utf-8') print(f) # f: <_io.TextIOWrapper name='yesterday2.lrc' mode='a' encoding='utf-8'> # a(append) 末尾追加, 若文件不存在,则先创建,再追加 f.write('Love u ') f.write('Hate u ') f.write('when i was yong i listen to the radio ') f.read() # io.UnsupportedOperation: not readable # 读取前5行 f = open('yesterday1.lrc','r',encoding='utf-8') for I in range(5): print(f.readline()) # f.readline() 读取一行 # 读取整个文件,第十行不打印 f = open('yesterday1.lrc','r',encoding='utf-8') print(f.readlines()) #读取整个文件,并以行为元素,按照文件内容顺序组成一个列表,比较适合读取小文件 ['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 ', '当我年少轻狂'] for index,line in enumerate(f.readlines()): # 枚举 if index == 9: print('-------------------优美的分割线-----------') continue print(line.strip()) # 对于处理大文件(比如大小为4G),f.readline()或f.readlines(),会将文件读出并存储于内存中,严重的消耗内存 f = open('yesterday1.lrc','r',encoding='utf-8') count = 0 for line in f: # 内存中始终存储一行,效率最高,此时f对象被视为迭代器 if count == 9: print('-------------------优美的分割线-----------') count += 1 continue print(line.strip()) count += 1 # f = open('yesterday2.lrc','r+',encoding='utf-8') # 读写 # f = open('yesterday2.lrc','w+',encoding='utf-8') # 写读 # f = open('yesterday2.lrc','a+',encoding='utf-8') # 追加读 # print(f.readline()) # print(f.readline()) # print(f.readline()) # print(f.tell()) # f.write('---------------perfect--------------- ') # f.write('---------------perfect--------------- ') # f.write('---------------perfect--------------- ') # f.write('---------------perfect--------------- ') # print(f.tell()) # f.seek(10) # print(f.readline()) # f.write('should be at the begining of the second line. ') # f = open('yesterday2.lrc','rb',encoding='utf-8') # 二进制读 # ValueError: binary mode doesn't take an encoding argument # f = open('yesterday2.lrc','rb') # 二进制读 (网络传输) # print(f.readline()) # print(f.readline()) # print(f.readline()) ''' b'---------------perfect--------------- ' b'---------------perfect--------------- ' b'---------------perfect--------------- ' ''' f = open('yesterday2.lrc','wb') # f.write('hello, binary') # TypeError: 'str' does not support the buffer interface f.write('hello, binary '.encode()) # 默认为'utf-8' f.close() # 手动关闭文件