对文件操作流程

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

现有文件如下

  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. 当我年少轻狂

yesterday.txt

基本操作 

  1. f=open("yesterday.txt",encoding='UTF-8') #打开文件句柄
  2. print(f.read()) #打印全部,读完之后,指针在文件最后,下次读时从文件最后开始读
  3.  
  4. for i in range(5):
  5. print(f.readline()) #打印前5行,读完之后,指针在文件第5行后,下次读时从文件第5行开始读
  6.  
  7. print(f.readlines()) #将文件作为一个列表读出来,每一行代表一个元素
  8.  
  9. #循环打印所有行,low的写法
  10. # 吃内存,内存保存全部行,需要将全部行写入内存后再一行行地读,当文件较大时,我们等待时间变长,并且内存也吃不消了
  11. for line in f.readlines():
  12. print(line.strip())
  13.  
  14. #循环打印除第10行之外的所有行,low的写法
  15. for index,line in enumerate(f.readlines()):
  16. if index==9:
  17. print('-------我是分割线----------')
  18. continue
  19. print(line.strip())
  20.  
  21. #循环打印所有行,high的写法
  22. #效率高,文件变成一个迭代器,读一行内存中删一行,内存中只保存一行,牛B了
  23. for line in f:
  24. print(line.strip())
  25.  
  26. #循环打印除第10行之外的所有行,high的写法
  27. count=0
  28. for line in f:
  29. if count == 9:
  30. print('-------我是分割线----------')
  31. count+=1
  32. continue
  33. print(line.strip())
  34. count += 1
  35.  
  36. print(f.tell()) #打印指针位置,开始位置0
  37. print(f.read(5)) #读文件的5个字符
  38. print(f.tell()) #此时指针位置是5
  39. print(f.seek(0)) #指针回到位置0
  40. print(f.readline()) #从头开始打印第一行
  41.  
  42. print(f.seekable()) #判断是否可以移动文件的光标位置,如果可以(比如说二进制,字符串文件),返回True,否则返回False
  43. #并不是所有的文件都是可以把光标移动的,因为Linux是一切皆文件,比如说tty文件就是不可以的
  44. print(f.encoding) #打印文件的编码格式
  45. print(f.fileno()) #返回文件句柄在内存中的编号,我们一般不会用到它
  46. # 操作系统有一个专门的接口,负责调度所有文件。Python读文件不是自己读的,是调用操作系统的IO,
  47. # 操作系统内部维护了一个类似于现在读了多少文件之类的列表,这就是在其中的编号。
  48. print(f.name) #打印文件名字
  49. print(f.isatty()) #判断文件是否是一个终端设备,比如说打印机、Linux上打开的terminal都属于终端设备,
  50. # 这个是你做一些底层的,比如说和打印机交互等可能会用得到。
  51. print(f.readable()) #判断文件是否可读
  52. print(f.writable()) #判断文件是否可写
  53. print(f.cloed) #判断文件是否已关闭
  54. f.close() #对文件操作完之后,一定要关闭文件
  1. #写文件时,是先将内容写入一个缓存中,当缓存满时再一次性将所有内容写入硬盘
  2. #flush()作用是强制将内容刷新到硬盘
  3. >>> f=open('test.txt','w')
  4. >>> f.write('hello1\n') #此时打开test.txt文件,发现文件为空
  5. 7
  6. >>> f.flush() #重新打开文件,文件显示一行hello1
  7. >>> f.write('hello2\n') #重新打开文件,文件未变还是只显示一行hello1
  8. 7
  9. >>> f.flush() #重新打开文件,发现hello2已写入文件
  10. >>> f.close()

f.flush()

  1. import sys,time
  2.  
  3. for i in range(20):
  4. sys.stdout.write('#')
  5. sys.stdout.flush() #如果没有这一句,则程序时先将所有的#写到缓存中,再一次性输出
  6. time.sleep(0.2)

flush()应用场景之进度条

  1. f=open("yesterday2.txt",'a',encoding='UTF-8') #文件句柄
  2. f.seek(5)
  3. f.truncate(10) #截取前10个字符,此时打开文件发现只剩前10个字符
  4. #此处seek方法没有作用,truncate方法默认就是从文件开头开始截取
  5. f.close()

f.truncate()

打开文件的模式有:

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

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

  • r+,读写模式。【可读;可写;可追加】
    1. #读写模式:可以打开文件读,追加,某些场景会用到
    2. f=open("yesterday2.txt",'r+',encoding='UTF-8')
    3. print(f.readline())
    4. print(f.readline())
    5. print(f.readline()) #读3行,此时光标在第3行末尾
    6. print(f.tell())
    7. f.write("This line shoud be at line3") #你认为新写入的这行应该在第3行末尾,但是实际上这行写在了整个文件末尾
    8. # Python2.X可以写到第二行开始部分,但是会覆盖文件原来的此处内容
    9. f.close()
  • w+,写读模式。
    1. #写读模式:没什么卵用
    2. f=open("yesterday2.txt",'w+',encoding='UTF-8') #写读模式,文件存在则清空,没有则创建
    3. print(f.readline())
    4. print(f.readline())
    5. print(f.readline()) #其实一行也读不出来,因为文件清空了
    6. f.write("---------line 1------------\n")
    7. f.write("---------line 2------------\n")
    8. f.write("---------line 3------------\n")
    9. f.write("---------line 4------------\n")
    10. print(f.tell())
    11. f.seek(10)
    12. print(f.readline())
    13. f.write("should be at the beginning of the second line")#你认为新写入的这行应该在第2行开始,但是实际上这这行追加到了文件末尾
    14. #Python2.X可以写到第二行开始部分,但是会覆盖文件原来的此处内容
    15. f.close()
  • a+,追加读模式。
    1. # 追加读模式:a追加模式是不可读的,a+追加读模式默认可读可追加
    2. f = open("yesterday2.txt", 'a+', encoding='UTF-8')
    3. print(f.readline()) #不知道为啥没读出来,也没报错?
    4. f.write("This line shoud be at the end of the file")
    5. f.close()

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

  • rb
    1. # rb:以二进制格式读文件
    2. #应用场景:网络传输等
    3. #Python3.X中网络传输一律用二进制模式,Python2.X中网络传输可以用二进制格式,也可以用字符串格式
    4. f = open("yesterday2.txt", 'rb')
    5. print(f.readline())
    6. print(f.readline())
    7. print(f.readline())
    8. f.close()
  • wb
    1. # wb:以二进制格式写文件
    2. #python2.X中二进制、字符串格式没什么区别,Python3.X中一定要区分开来
    3. f = open("yesterday2.txt", 'wb')
    4. #f.write("Hello Binary!") #以字符串格式写会报错
    5. f.write("Hello Binary!".encode())
    6. f.close()
  • ab

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)。
因为在Windows上换行符是\r\n,在Linux上是\n,U可以统一双方的适配,比如在Linux上打开在Windows上的文件可以用rU。用的比较少,了解即可。

  • rU
  • r+U

 其他语法

  1. def close(self): # real signature unknown; restored from __doc__
  2. """
  3. Close the file.
  4.  
  5. A closed file cannot be used for further I/O operations. close() may be
  6. called more than once without error.
  7. """
  8. pass
  9.  
  10. def fileno(self, *args, **kwargs): # real signature unknown
  11. """ Return the underlying file descriptor (an integer). """
  12. pass
  13.  
  14. def isatty(self, *args, **kwargs): # real signature unknown
  15. """ True if the file is connected to a TTY device. """
  16. pass
  17.  
  18. def read(self, size=-1): # known case of _io.FileIO.read
  19. """
  20. 注意,不一定能全读回来
  21. Read at most size bytes, returned as bytes.
  22.  
  23. Only makes one system call, so less data may be returned than requested.
  24. In non-blocking mode, returns None if no data is available.
  25. Return an empty bytes object at EOF.
  26. """
  27. return ""
  28.  
  29. def readable(self, *args, **kwargs): # real signature unknown
  30. """ True if file was opened in a read mode. """
  31. pass
  32.  
  33. def readall(self, *args, **kwargs): # real signature unknown
  34. """
  35. Read all data from the file, returned as bytes.
  36.  
  37. In non-blocking mode, returns as much as is immediately available,
  38. or None if no data is available. Return an empty bytes object at EOF.
  39. """
  40. pass
  41.  
  42. def readinto(self): # real signature unknown; restored from __doc__
  43. """ Same as RawIOBase.readinto(). """
  44. pass #不要用,没人知道它是干嘛用的
  45.  
  46. def seek(self, *args, **kwargs): # real signature unknown
  47. """
  48. Move to new file position and return the file position.
  49.  
  50. Argument offset is a byte count. Optional argument whence defaults to
  51. SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
  52. are SEEK_CUR or 1 (move relative to current position, positive or negative),
  53. and SEEK_END or 2 (move relative to end of file, usually negative, although
  54. many platforms allow seeking beyond the end of a file).
  55.  
  56. Note that not all file objects are seekable.
  57. """
  58. pass
  59.  
  60. def seekable(self, *args, **kwargs): # real signature unknown
  61. """ True if file supports random-access. """
  62. pass
  63.  
  64. def tell(self, *args, **kwargs): # real signature unknown
  65. """
  66. Current file position.
  67.  
  68. Can raise OSError for non seekable files.
  69. """
  70. pass
  71.  
  72. def truncate(self, *args, **kwargs): # real signature unknown
  73. """
  74. Truncate the file to at most size bytes and return the truncated size.
  75.  
  76. Size defaults to the current file position, as returned by tell().
  77. The current file position is changed to the value of size.
  78. """
  79. pass
  80.  
  81. def writable(self, *args, **kwargs): # real signature unknown
  82. """ True if file was opened in a write mode. """
  83. pass
  84.  
  85. def write(self, *args, **kwargs): # real signature unknown
  86. """
  87. Write bytes b to file, return number written.
  88.  
  89. Only makes one system call, so not all of the data may be written.
  90. The number of bytes actually written is returned. In non-blocking mode,
  91. returns None if the write would block.
  92. """
  93. pass

 with语句

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

  1. with open('log','r') as f:
  2.  
  3. ...

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

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

  1. #python开发规范:一行代码不要超过80个字符,所以打开多个文件时最好分为多行,如下
    with open("yesterday.txt",'r',encoding='UTF-8') as f1,\
    open("yesterday2.txt", 'w', encoding='UTF-8') as f2:
    pass

修改文件

  1. #VIM修改文件的方式:先把文件读到内存中,在内存中修改,之后再把修改后的文件读出来覆盖原文件
  2. #另一种修改文件的方式,将文件修改后,写到另一个新文件中,如下
  3. f=open("yesterday.txt",'r',encoding='UTF-8')
  4. f_new=open("yesterday.bak",'w',encoding='UTF-8')
  5.  
  6. for line in f:
  7. if "有那么多肆意的快乐等我享受" in line:
  8. line=line.replace("有那么多肆意的快乐等我享受","有那么多肆意的快乐等Alex享受")
  9. f_new.write(line)
  10.  
  11. f.close()
  12. f_new.close()

Python3学习之路~2.7 文件操作的更多相关文章

  1. Python3学习之路~2.8 文件操作实现简单的shell sed替换功能

    程序:实现简单的shell sed替换功能 #实现简单的shell sed替换功能,保存为file_sed.py #打开命令行输入python file_sed.py 我 Alex,回车后会把文件中的 ...

  2. Python3学习之路~2.6 集合操作

    集合是一个无序的,不重复的数据组合,它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 常用操作 >>> list1 = ...

  3. Python3学习之路~2.3 字符串操作

    字符串操作 特性:不可修改 name="my \tname is alex" print(name.capitalize()) #首字母变大写 print('Alex LI'.ca ...

  4. Python3学习之路~2.4 字典操作

    字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划.字母来查对应页的详细内容. 定义字典(dictionary) info = { 'stu1101': "Amy ...

  5. Python3学习之路~0 目录

    目录 Python3学习之路~2.1 列表.元组操作 Python3学习之路~2.2 简单的购物车程序 Python3学习之路~2.3 字符串操作 Python3学习之路~2.4 字典操作 Pytho ...

  6. [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  7. Python学习系列(五)(文件操作及其字典)

    Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件      在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...

  8. Html5 学习系列(四)文件操作API

    原文:Html5 学习系列(四)文件操作API 引言 在之前我们操作本地文件都是使用flash.silverlight或者第三方的activeX插件等技术,由于使用了这些技术后就很难进行跨平台.或者跨 ...

  9. NO.3:自学python之路------集合、文件操作、函数

    引言 本来计划每周完成一篇Python的自学博客,由于上一篇到这一篇遇到了过年.开学等杂事,导致托更到现在.现在又是一个新的学期,春天也越来越近了(冷到感冒).好了,闲话就说这么多.开始本周的自学Py ...

随机推荐

  1. 6、二、App Components(应用程序组件):1、Intents and Intent Filters(意图和意图过滤器)

    1.Intents and Intent Filters(意图和意图过滤器) 1.0.Intents and Intent Filters(意图和意图过滤器) An Intent is a messa ...

  2. Win10系统安装过程小记

    1.网上下载ghost系统http://win10.jysmac.cn/win1064.html 2.使用系统自带的激活工具激活 3.到windows官网下载更新工具更新系统,重新安装https:// ...

  3. POJ 1661 Help Jimmy(DP/最短路)

    Help Jimmy Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 14980 Accepted: 4993 Descripti ...

  4. eclipse无法连接到makertplace

    Eclipse需要安装一个Jcoco的插件,但是连接Eclipse Market的时候,总是出现如下的报错: Cannot open Eclipse Marketplace Cannot instal ...

  5. javascript基础学习系列-DOM盒子模型常用属性

    最近在学习DOM盒子模型,各种属性看着眼花缭乱,下面根据三个系列来分别介绍一下: client系列 clientWidth :width+(padding-left)+(padding-right)— ...

  6. 洛谷P1042 乒乓球【模拟】

    题目背景 国际乒联现在主席沙拉拉自从上任以来就立志于推行一系列改革,以推动乒乓球运动在全球的普及.其中111111分制改革引起了很大的争议,有一部分球员因为无法适应新规则只能选择退役.华华就是其中一位 ...

  7. tensorflow 添加一个全连接层

    对于一个全连接层,tensorflow都为我们封装好了. 使用:tf.layers.dense() tf.layers.dense( inputs, units, activation=None, u ...

  8. 信1705-2 软工作业最大重复词查询思路: (1)将文章(一个字符串存储)按空格进行拆分(split)后,存储到一个字符串(单词)数组中。 (2)定义一个Map,key是字符串类型,保存单词;value是数字类型,保存该单词出现的次数。 (3)遍历(1)中得到的字符串数组,对于每一个单词,考察Map的key中是否出现过该单词,如果没出现过,map中增加一个元素,key为该单词,value为1(

    通过学习学会了文本的访问,了解一点哈希表用途.经过网上查找做成了下面查询文章重复词的JAVA程序. 1 思 思路: (1)将文章(一个字符串存储)按空格进行拆分(split)后,存储到一个字符串(单词 ...

  9. node 下查看安装插件的最新版本号的方法

    例如查看extract-text-webpack-plugin的最新版本号 (不一定时本地安装的插件的版本号) npm view extract-text-webpack-plugin version ...

  10. CHARACTER SET

    mysql> show tables; +-----------------+ | Tables_in_w0811 | +-----------------+ | t | | w_engine ...