文件操作,顾名思义,就是对磁盘上已经存在的文件进行各种操作,文本文件就是读和写。

1. 文件的操作流程

(1)打开文件,得到文件句柄并赋值给一个变量

(2)通过句柄对文件进行操作

(3)关闭文件

现有文件

  1. 昔闻洞庭水,今上岳阳楼。
  2. 吴楚东南坼,乾坤日夜浮。
  3. 亲朋无一字,老病有孤舟。
  4. 戎马关山北,凭轩涕泗流。

2. 文件的打开模式

打开文件的模式:

三种基本模式:

1. r,只读模式(默认)

2. w,只写模式。(不可读,不存在文件则创建,存在则删除内容)

3. a,追加模式。(不存在文件则创建,存在则在文件末尾追加内容)

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

4.r+,可读写。(读文件从文件起始位置,写文件则跳转到文件末尾添加)

5.w+,可写读。(文件不存在就创建文件,文件存在则清空文件,之后可写可读)

6.a+,可读写,读和写都从文件末尾开始。

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

7.rU

8.r+U

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

9. rb

10.wb

11.ab

3.文件具体操作

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

具体操作

  1. open()打开文件
  2. close()关闭文件
  3.  
  4. f = open('登岳阳楼','r')
  5. print(f.read()) #读取所有
  6. >>>
  7. 昔闻洞庭水,今上岳阳楼。
  8. 吴楚东南坼,乾坤日夜浮。
  9. 亲朋无一字,老病有孤舟。
  10. 戎马关山北,凭轩涕泗流
  11.  
  12. print(f.read(5)) #读取5个字
  13. >>>
  14. 昔闻洞庭水
  15.  
  16. print(f.readline()) #读取一行
  17. print(f.readline()) #继续执行,读取下一行
  18. >>>
  19. 昔闻洞庭水,今上岳阳楼。
  20.  
  21. 吴楚东南坼,乾坤日夜浮。
  22.  
  23. print(f.readlines()) #以列表形式读出文件
  24. >>>
  25. ['昔闻洞庭水,今上岳阳楼。\n', '吴楚东南坼,乾坤日夜浮。\n', '亲朋无一字,老病有孤舟。\n', '戎马关山北,凭轩涕泗流。']
  26. for i in f.readlines():
  27. print(i)
  28. >>>
  29. 昔闻洞庭水,今上岳阳楼。
  30.  
  31. 吴楚东南坼,乾坤日夜浮。
  32.  
  33. 亲朋无一字,老病有孤舟。
  34.  
  35. 戎马关山北,凭轩涕泗流。
  36. 还可以用:(建议这种方法)
  37. for i in f:
  38. print(i)
  39.  
  40. print(f.tell()) #指出光标所在位置r模式打开文件默认光标在初始位置0
  41. >>>
  42. 0
  43.  
  44. f = open('登岳阳楼','r',encoding='utf-8')
  45. print(f.tell())
  46. f.seek(5)
  47. print(f.tell())
  48. >>>
  49. 0
  50. 5
  51. f.seek() 用于调整光标位置类似于下载时的断线重连
  52.  
  53. f = open('登岳阳楼','w',encoding='utf-8')
  54. f.write('hello world')
  55. >>>
  56. hello world
  57. #用w模式打开文件将会清除文件所有内容,再添加write()中的内容
  58.  
  59. f.flush() #写文件时,写的内容不会直接写到文件中,而是保存在内存里,等文件close后才写入文件,flush()方法就是将内存中的内容立刻写入文件。可用于进度条
  60.  
  61. f = open('登岳阳楼','w',encoding='utf-8')
  62. f.write('hello world')
  63. f.truncate(4) #截断内容
  64. >>>
  65. hell

with语句

为了防止我们在对文件操作后忘记close()文件,可以通过with语句对文件操作,

  1. with open('登岳阳楼','r',encoding='utf-8') as f:
  2. print(f.read())
  3. >>>
  4. 昔闻洞庭水,今上岳阳楼。
  5. 吴楚东南坼,乾坤日夜浮。
  6. 亲朋无一字,老病有孤舟。
  7. 戎马关山北,凭轩涕泗流。

当with语句执行完毕,文件就默认关闭了。

Python的文件操作的更多相关文章

  1. Python :open文件操作,配合read()使用!

    python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...

  2. Python 常见文件操作的函数示例(转)

    转自:http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html # -*-coding:utf8 -*- ''''' Python常 ...

  3. 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容

     孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...

  4. 孤荷凌寒自学python第三十三天python的文件操作初识

     孤荷凌寒自学python第三十三天python的文件操作初识 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天开始自学python的普通 文件操作部分的内容. 一.python的文件打开 ...

  5. python中文件操作的六种模式及对文件某一行进行修改的方法

    一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...

  6. python中文件操作的其他方法

    前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r', ...

  7. Python常见文件操作的函数示例

    # -*-coding:utf8 -*- ''''' Python常见文件操作示例 os.path 模块中的路径名访问函数 分隔 basename() 去掉目录路径, 返回文件名 dirname() ...

  8. python的文件操作及简单的用例

    一.python的文件操作介绍 1.文件操作函数介绍 open() 打开一个文件 语法:open(file, mode='r', buffering=-1, encoding=None, errors ...

  9. python基本文件操作

    python文件操作 python的文件操作相对于java复杂的IO流简单了好多,只要关心文件的读和写就行了 基本的文件操作 要注意的是,当不存在某路径的文件时,w,a模式会自动新建此文件夹,当读模式 ...

  10. [转]python file文件操作--内置对象open

    python file文件操作--内置对象open   说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...

随机推荐

  1. Java:泛型基础

    泛型 引入泛型 传统编写的限制: 在Java中一般的类和方法,只能使用具体的类型,要么是基本数据类型,要么是自定义类型.如果要编写可以应用于多种类型的代码,这种刻板的限制就会束缚很多! 解决这种限制的 ...

  2. C#的扩展方法解析

    在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到. 继承的有关特性的使用所带来的问题:对象的继 ...

  3. 3.C#面向对象基础聊天机器人

    基于控制台的简单版的聊天机器人,词库可以自己添加. 聊天机器人1.0版本 源码如下: using System; using System.Collections.Generic; using Sys ...

  4. 利用Python进行数据分析(15) pandas基础: 字符串操作

      字符串对象方法 split()方法拆分字符串: strip()方法去掉空白符和换行符: split()结合strip()使用: "+"符号可以将多个字符串连接起来: join( ...

  5. Python中的类、对象、继承

    类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...

  6. PyQt4入门学习笔记(二)

    之前第一篇介绍了pyqt4的大小,移动位置,消息提示.这次我们介绍菜单和工具栏 QtGui.QmainWindow这个类可以给我们提供一个创建带有状态栏.工具栏和菜单栏的标准的应用. 状态栏 状态栏是 ...

  7. IL实现简单的IOC容器

    既然了解了IL的接口和动态类之间的知识,何不使用进来项目实验一下呢?而第一反应就是想到了平时经常说的IOC容器,在园子里搜索了一下也有这类型的文章http://www.cnblogs.com/kkll ...

  8. 周末惊魂:因struts2 016 017 019漏洞被入侵,修复。

    入侵(暴风雨前的宁静) 下午阳光甚好,想趁着安静的周末静下心来写写代码.刚过一个小时,3点左右,客服MM找我,告知客户都在说平台登录不了(我们有专门的客户qq群).看了下数据库连接数,正常.登录阿里云 ...

  9. python学习笔记(基础四:模块初识、pyc和PyCodeObject是什么)

    一.模块初识(一) 模块,也叫库.库有标准库第三方库. 注意事项:文件名不能和导入的模块名相同 1. sys模块 import sys print(sys.path) #打印环境变量 print(sy ...

  10. Qt信号与槽自动关联机制

    参考链接1:http://blog.csdn.net/skyhawk452/article/details/6121407 参考链接2:http://blog.csdn.net/memory_exce ...