Python的文件操作
文件操作,顾名思义,就是对磁盘上已经存在的文件进行各种操作,文本文件就是读和写。
1. 文件的操作流程
(1)打开文件,得到文件句柄并赋值给一个变量
(2)通过句柄对文件进行操作
(3)关闭文件
现有文件
- 昔闻洞庭水,今上岳阳楼。
- 吴楚东南坼,乾坤日夜浮。
- 亲朋无一字,老病有孤舟。
- 戎马关山北,凭轩涕泗流。
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.文件具体操作
- def read(self, size=-1): # known case of _io.FileIO.read
- """
- 注意,不一定能全读回来
- Read at most size bytes, returned as bytes.
- Only makes one system call, so less data may be returned than requested.
- In non-blocking mode, returns None if no data is available.
- Return an empty bytes object at EOF.
- """
- return ""
- def readline(self, *args, **kwargs):
- pass
- def readlines(self, *args, **kwargs):
- pass
- def tell(self, *args, **kwargs): # real signature unknown
- """
- Current file position.
- Can raise OSError for non seekable files.
- """
- pass
- def seek(self, *args, **kwargs): # real signature unknown
- """
- Move to new file position and return the file position.
- Argument offset is a byte count. Optional argument whence defaults to
- SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
- are SEEK_CUR or 1 (move relative to current position, positive or negative),
- and SEEK_END or 2 (move relative to end of file, usually negative, although
- many platforms allow seeking beyond the end of a file).
- Note that not all file objects are seekable.
- """
- pass
- def write(self, *args, **kwargs): # real signature unknown
- """
- Write bytes b to file, return number written.
- Only makes one system call, so not all of the data may be written.
- The number of bytes actually written is returned. In non-blocking mode,
- returns None if the write would block.
- """
- pass
- def flush(self, *args, **kwargs):
- pass
- def truncate(self, *args, **kwargs): # real signature unknown
- """
- Truncate the file to at most size bytes and return the truncated size.
- Size defaults to the current file position, as returned by tell().
- The current file position is changed to the value of size.
- """
- pass
- def close(self): # real signature unknown; restored from __doc__
- """
- Close the file.
- A closed file cannot be used for further I/O operations. close() may be
- called more than once without error.
- """
- pass
- ##############################################################less usefull
- def fileno(self, *args, **kwargs): # real signature unknown
- """ Return the underlying file descriptor (an integer). """
- pass
- def isatty(self, *args, **kwargs): # real signature unknown
- """ True if the file is connected to a TTY device. """
- pass
- def readable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a read mode. """
- pass
- def readall(self, *args, **kwargs): # real signature unknown
- """
- Read all data from the file, returned as bytes.
- In non-blocking mode, returns as much as is immediately available,
- or None if no data is available. Return an empty bytes object at EOF.
- """
- pass
- def seekable(self, *args, **kwargs): # real signature unknown
- """ True if file supports random-access. """
- pass
- def writable(self, *args, **kwargs): # real signature unknown
- """ True if file was opened in a write mode. """
- pass
- 操作方法介绍
具体操作
- open()打开文件
- close()关闭文件
- f = open('登岳阳楼','r')
- print(f.read()) #读取所有
- >>>
- 昔闻洞庭水,今上岳阳楼。
- 吴楚东南坼,乾坤日夜浮。
- 亲朋无一字,老病有孤舟。
- 戎马关山北,凭轩涕泗流
- print(f.read(5)) #读取5个字
- >>>
- 昔闻洞庭水
- print(f.readline()) #读取一行
- print(f.readline()) #继续执行,读取下一行
- >>>
- 昔闻洞庭水,今上岳阳楼。
- 吴楚东南坼,乾坤日夜浮。
- print(f.readlines()) #以列表形式读出文件
- >>>
- ['昔闻洞庭水,今上岳阳楼。\n', '吴楚东南坼,乾坤日夜浮。\n', '亲朋无一字,老病有孤舟。\n', '戎马关山北,凭轩涕泗流。']
- for i in f.readlines():
- print(i)
- >>>
- 昔闻洞庭水,今上岳阳楼。
- 吴楚东南坼,乾坤日夜浮。
- 亲朋无一字,老病有孤舟。
- 戎马关山北,凭轩涕泗流。
- 还可以用:(建议这种方法)
- for i in f:
- print(i)
- print(f.tell()) #指出光标所在位置r模式打开文件默认光标在初始位置0
- >>>
- 0
- f = open('登岳阳楼','r',encoding='utf-8')
- print(f.tell())
- f.seek(5)
- print(f.tell())
- >>>
- 0
- 5
- f.seek() 用于调整光标位置类似于下载时的断线重连
- f = open('登岳阳楼','w',encoding='utf-8')
- f.write('hello world')
- >>>
- hello world
- #用w模式打开文件将会清除文件所有内容,再添加write()中的内容
- f.flush() #写文件时,写的内容不会直接写到文件中,而是保存在内存里,等文件close后才写入文件,flush()方法就是将内存中的内容立刻写入文件。可用于进度条
- f = open('登岳阳楼','w',encoding='utf-8')
- f.write('hello world')
- f.truncate(4) #截断内容
- >>>
- hell
with语句
为了防止我们在对文件操作后忘记close()文件,可以通过with语句对文件操作,
- with open('登岳阳楼','r',encoding='utf-8') as f:
- print(f.read())
- >>>
- 昔闻洞庭水,今上岳阳楼。
- 吴楚东南坼,乾坤日夜浮。
- 亲朋无一字,老病有孤舟。
- 戎马关山北,凭轩涕泗流。
当with语句执行完毕,文件就默认关闭了。
Python的文件操作的更多相关文章
- Python :open文件操作,配合read()使用!
python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...
- Python 常见文件操作的函数示例(转)
转自:http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html # -*-coding:utf8 -*- ''''' Python常 ...
- 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容
孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...
- 孤荷凌寒自学python第三十三天python的文件操作初识
孤荷凌寒自学python第三十三天python的文件操作初识 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天开始自学python的普通 文件操作部分的内容. 一.python的文件打开 ...
- python中文件操作的六种模式及对文件某一行进行修改的方法
一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...
- python中文件操作的其他方法
前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r', ...
- Python常见文件操作的函数示例
# -*-coding:utf8 -*- ''''' Python常见文件操作示例 os.path 模块中的路径名访问函数 分隔 basename() 去掉目录路径, 返回文件名 dirname() ...
- python的文件操作及简单的用例
一.python的文件操作介绍 1.文件操作函数介绍 open() 打开一个文件 语法:open(file, mode='r', buffering=-1, encoding=None, errors ...
- python基本文件操作
python文件操作 python的文件操作相对于java复杂的IO流简单了好多,只要关心文件的读和写就行了 基本的文件操作 要注意的是,当不存在某路径的文件时,w,a模式会自动新建此文件夹,当读模式 ...
- [转]python file文件操作--内置对象open
python file文件操作--内置对象open 说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...
随机推荐
- Java:泛型基础
泛型 引入泛型 传统编写的限制: 在Java中一般的类和方法,只能使用具体的类型,要么是基本数据类型,要么是自定义类型.如果要编写可以应用于多种类型的代码,这种刻板的限制就会束缚很多! 解决这种限制的 ...
- C#的扩展方法解析
在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到. 继承的有关特性的使用所带来的问题:对象的继 ...
- 3.C#面向对象基础聊天机器人
基于控制台的简单版的聊天机器人,词库可以自己添加. 聊天机器人1.0版本 源码如下: using System; using System.Collections.Generic; using Sys ...
- 利用Python进行数据分析(15) pandas基础: 字符串操作
字符串对象方法 split()方法拆分字符串: strip()方法去掉空白符和换行符: split()结合strip()使用: "+"符号可以将多个字符串连接起来: join( ...
- Python中的类、对象、继承
类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...
- PyQt4入门学习笔记(二)
之前第一篇介绍了pyqt4的大小,移动位置,消息提示.这次我们介绍菜单和工具栏 QtGui.QmainWindow这个类可以给我们提供一个创建带有状态栏.工具栏和菜单栏的标准的应用. 状态栏 状态栏是 ...
- IL实现简单的IOC容器
既然了解了IL的接口和动态类之间的知识,何不使用进来项目实验一下呢?而第一反应就是想到了平时经常说的IOC容器,在园子里搜索了一下也有这类型的文章http://www.cnblogs.com/kkll ...
- 周末惊魂:因struts2 016 017 019漏洞被入侵,修复。
入侵(暴风雨前的宁静) 下午阳光甚好,想趁着安静的周末静下心来写写代码.刚过一个小时,3点左右,客服MM找我,告知客户都在说平台登录不了(我们有专门的客户qq群).看了下数据库连接数,正常.登录阿里云 ...
- python学习笔记(基础四:模块初识、pyc和PyCodeObject是什么)
一.模块初识(一) 模块,也叫库.库有标准库第三方库. 注意事项:文件名不能和导入的模块名相同 1. sys模块 import sys print(sys.path) #打印环境变量 print(sy ...
- Qt信号与槽自动关联机制
参考链接1:http://blog.csdn.net/skyhawk452/article/details/6121407 参考链接2:http://blog.csdn.net/memory_exce ...