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参数表示的需要打开文件的相对路径(当前 ...
随机推荐
- Log4net入门(回滚日志文件篇)
在上一篇Log4net(日志文件篇)中,我们使用"log4net.Appender.FileAppender"将日志信息输出到一个单一的文件中,随着应用程序的持续使用,该日志文件会 ...
- 学习总结 之 WebApi服务监控 log4net记录监控日志
在请求WebApi 的时候,我们更想知道在请求数据的时候,调用了哪个接口传了什么参数过来,调用这个Action花了多少时间,有没有人恶意请求.我们可以通过记录日志,对Action进行优化,可以通过日志 ...
- OpenNLP:驾驭文本,分词那些事
OpenNLP:驾驭文本,分词那些事 作者 白宁超 2016年3月27日19:55:03 摘要:字符串.字符数组以及其他文本表示的处理库构成大部分文本处理程序的基础.大部分语言都包括基本的处理库,这也 ...
- 百度EChart3初体验
由于项目需要在首页搞一个订单数量的走势图,经过多方查找,体验,感觉ECharts不错,封装的很细,我们只需要看自己需要那种类型的图表,搞定好自己的json数据就OK.至于说如何体现出来,官网的教程很详 ...
- Redis简单案例(一) 网站搜索的热搜词
对于一个网站来说,无论是商城网站还是门户网站,搜索框都是有一个比较重要的地位,它的存在可以说是 为了让用户更快.更方便的去找到自己想要的东西.对于经常逛这个网站的用户,当然也会想知道在这里比较“火” ...
- 查看Sql Server被锁的表以及解锁
查看被锁表: select spId from master..SysProcesses where db_Name(dbID) = '数据库名称' and spId <> @@SpId ...
- FPGA旋转编码器的实现
module pmodenc( clk, rst_n, A, B, BTN,// A_Debounce,// B_Debounce,// BTN_Debounce,// Rotary_right,// ...
- 每天一个设计模式-3 适配器模式(Adapteer)
每天一个设计模式-3 适配器模式(Adapteer) 1.现实中的情况 旧式电脑的硬盘是串口的,直接与硬盘连接,新硬盘是并口的,显然新硬盘不能直接连在电脑上,于是就有了转接线.好了,今天的学习主题出来 ...
- JavaScript 9种类型
Undefined . Null . Boolean . String . Number . Object . Reference .List .Completion
- 【原】JAVA开发环境搭建
1.JDK下载并安装,以jdk-7u45-windows-i586.exe为例(注意JDK的安装和JRE的安装是分开的) 2.“我的电脑”右键属性,找到“高级系统设置”,找到“高级”tab下的“环境变 ...