python3.x 基础三:文件IO
打开文件的两种方式
1.直接打开文件并赋值给变量,打开后得到操作句柄,但不会自动关闭
- file = open('文件名‘,'打开模式',’编码‘)
fd = open('../config/file1.txt','r',encoding='utf-8')
2.使用with子句,打开后文件会自动关闭,建议使用,并可以同时打开多个文件
with open('../config/file1.txt','r',encoding='utf-8') as fd1,\
open('../config/file2.txt','r',encoding='utf-8') as fd2:
print("I had open two files")
打开文件的8种模式
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
1.’r',默认模式,参数可以不写,打开只读文件,写入报错
>>> fd = open('../config/file1.txt','r',encoding='utf-8')
>>> fd.write('java c rubby')
Traceback (most recent call last):
File "<stdin>", line , in <module>
io.UnsupportedOperation: not writable
2.‘w’,先truncate原文件,后写入,不可读,文件不存在则创建
>>> fd = open('../config/file1.txt','w',encoding='utf-8')
>>> print(fd.read())
Traceback (most recent call last):
File "<stdin>", line , in <module>
io.UnsupportedOperation: not readable
>>> fd.write('java rubby go')
>>> fd.close()
>>> fd = open('../config/file1.txt','r',encoding='utf-8')
>>> fd.read()
'java rubby go'
3.'x',创建新文件,打开并写入,如果文件已经存在,则报错
>>> fd = open('../config/file21.txt','x',encoding='utf-8' )
>>> fd.read()
Traceback (most recent call last):
File "<stdin>", line , in <module>
io.UnsupportedOperation: not readable
>>> fd.write('')
>>> fd.close()
>>> fd = open('../config/file21.txt','r',encoding='utf-8')
>>> fd.read()
''
>>> fd.close()
>>> fd = open('../config/file21.txt','x',encoding='utf-8')
Traceback (most recent call last):
File "<stdin>", line , in <module>
FileExistsError: [Errno ] File exists: '../config/file21.txt'
4.’a',追加写内容到文件末尾
>>> fd = open('../config/file1.txt','a',encoding='utf-8')
>>> fd.write('linux windows aix')
17
>>> fd.close()
>>> fd = open('../config/file1.txt','r',encoding='utf-8')
>>> fd.read()
'java rubby golinux windows aix'
5.'b',二进制模式,比如流文件mp3,并且需要同时指定一种读写模式
>>> fd = open('/tmp/Front_Right.wav','b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Must have exactly one of create/read/write/append mode and at most one plus
>>> fd = open('/tmp/Front_Right.wav','rb')
>>> fd1 = open('/tmp/Front_Right.wav','wb')
>>> fd2 = open('/tmp/Front_Right.wav','ab')
>>> fd2 = open('/tmp/Front_Right.wav','w+b')
>>> fd2 = open('/tmp/Front_Right.wav','r+b')
6.'t',文本模式,默认打开文本并读取模式rt
7.'+',打开硬盘文件读写
- r+,打开并写入
>>> fd = open('../config/file1.txt','r+',encoding='utf-8')
>>> fd.read()
'java rubby golinux windows aix'
>>> fd.write("mage")
4
>>> fd.seek(0)
0
>>> fd.read()
'java rubby golinux windows aixmage'- w+,打开文件读写,文件存在则覆盖,不存在则创建
>>> fd = open('../config/file4.txt','w+',encoding='utf-8')
>>> fd.write('guangzhou')
9
>>> fd.seek(0)
0
>>> fd.read()
'guangzhou'
>>> fd.seek(0)
0
>>> fd.write('hangzhou')
8
>>> fd.seek(0)
0
>>> fd.read()
'hangzhouu'- a+,打开文件读写,存在则将指针置于末尾,不存在则创建新文件
>>> fd = open('../config/file4.txt','a+',encoding='utf-8')
>>> fd.read()
''
>>> fd.seek(0)
0
>>> fd.read()
'hangzhouu'
>>> fd.close()
>>> fd = open('../config/file4.txt','a+',encoding='utf-8')
>>> fd.write('beijing')
7
>>> fd.read()
''
>>> fd.seek(0)
0
>>> fd.read()
'hangzhouubeijing'- rb+, wb+, ab+ 对象是二进制,其他以上面一样
8.‘U’,deprecated
指针位置
1.f.tell(),告知字符指针位置
2.f.seek(),移动字符指针位置,f.seek(0)文件开头
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.tell()
0
>>> fd.seek(0)
0
>>> fd.tell()
0
>>> fd.read(1)
'h'
>>> fd.tell()
1
>>> fd.read(2)
'an'
>>> fd.tell()
3
>>> fd.seek(0)
0
>>> fd.readline()
'hangzhouubeijing\n'
>>> fd.tell()
17
读取文件的4个read,默认从头开始读,并将将指针留在行尾
1.fd.read(size)
- 默认省略size,size为整型,字符个数
- 读取全部内容到内存,并将指针留在行尾
- 大文件读取不要用,占内存
- 返回的是字符串类型
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.read()
'hangzhouubeijing'
>>> fd.seek(0)
0
>>> fd.read(1)
'h'
>>> fd.read(2)
'an'
>>> fd.read(3)
'gzh'
>>> fd.seek(0)
0
>>> fd.read(6)
'hangzh'
2.fd.readline(size)
- 默认一行行读取,size与上面一样
- 占用内存小
- 每行结尾带换行符
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.readline()
'hangzhouubeijing\n'
>>> fd.readline()
'shenzhen\n'
>>> fd.readline()
'shanghai\n'
>>> fd.readline(1)
'a'
>>> fd.readline(2)
'nh'
>>> fd.readline()
'ui\n'
>>> fd.readline()
'guangdong\n'
>>> fd.readline()
'zhejiang'
>>> fd.readline()
''
3.fd.readlines(size)
- 讲文本全部转换成列表,size表示下标
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.readlines()
['hangzhouubeijing\n', 'shenzhen\n', 'shanghai\n', 'anhui\n', 'guangdong\n', 'zhejiang']
>>> fd.seek(0)
0
>>> fd.readlines(1)
['hangzhouubeijing\n']
>>> fd.readlines()
['shenzhen\n', 'shanghai\n', 'anhui\n', 'guangdong\n', 'zhejiang']
4.fd.readable()
- 返回布尔值,判断文件是否可读
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.readable()
True
循环遍历迭代文本内容对象(遍历操作都可以这么干)
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> for line in fd:
... print(line)
...
hangzhouubeijing
shenzhen
shanghai
anhui
guangdong
zhejiang
>>> fd.seek(0)
0
>>> for index,line in enumerate(fd.readlines()):
... print(index,line)
...
0 hangzhouubeijing
1 shenzhen
2 shanghai
3 anhui
4 guangdong
5 zhejiang
>>>
其他方法
close(self, /) 关闭打开的文件
- | Flush and close the IO object.
- |
- | This method has no effect if the file is already closed.
detach(self, /) 干嘛用?
- | Separate the underlying buffer from the TextIOBase and return it.
- | After the underlying buffer has been detached, the TextIO is in an
- | unusable state.
>>> fd.detach()
<_io.BufferedReader name='../config/file4.txt'>
>>> fd.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: underlying buffer has been detached
fileno(self, /) 返回文件描述符,干嘛用?
- | Returns underlying file descriptor if one exists.
- | OSError is raised if the IO object does not use a file descriptor.
>>> fd = open('../config/file4.txt','r',encoding='utf-8')
>>> fd.fileno()
4
>>> fd = open('../config/filexxx.txt','w+',encoding='utf-8')
>>> fd.fileno()
3
flush(self, /) 将缓存立即写入硬盘,提高效率
- | Flush write buffers, if applicable.
- | This is not implemented for read-only and non-blocking streams.
import time
import sys
for i in range(40):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
isatty(self, /) 是否连接到终端设备
- | Return whether this is an 'interactive' stream.
- | Return False if it can't be determined.
seekable(self, /)
- | Return whether object supports random access.
- | If False, seek(), tell() and truncate() will raise OSError.
- | This method may need to do a test seek().
truncate(self, pos=None, /)
- | Truncate file to size bytes.
- | File pointer is left unchanged. Size defaults to the current IO
- | position as reported by tell(). Returns the new size.
>>> fd = open('../config/file4.txt','r+',encoding='utf-8')
>>> fd.truncate()
0
writable(self, /) 判断文件是否以写模式打开
| Return whether object was opened for writing.
>>> fd = open('../config/file4.txt','r+',encoding='utf-8')
>>> fd.writable()
True
>>> fd = open('../config/file1.txt','r',encoding='utf-8')
>>> fd.writable()
False
修改文件的两种方式:
1.全部读入内存,修改完毕之后覆盖写入源文件
2.一行一行读取内存,修改完毕之后写入新文件,用新文件覆盖旧文件
练习一:实现sed替换功能
练习二:修改haproxy配置文件
python3.x 基础三:文件IO的更多相关文章
- Python 基础三 文件 函数
今天回顾一下之前学的文件操作相关知识点,对于文件的操作,主要有一下几部分构成: 一.文件的基础知识 1.文件操作的基本流程 文件操作其实可以分成三大部分: 1.打开文件,获取文件句柄并赋予一个变量 2 ...
- python3【基础】-文件操作
1. python对文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件操作 关闭文件 现有如下文件: 昨夜寒蛩不住鸣. 惊回千里梦,已三更. 起来独自绕阶行. 人悄悄,帘外月胧明. ...
- python3.x 基础三:字符集问题
总结了一张表,更详细信息百度百科: 序号 年份 编码 标准协会 特点 二进制长度 字符长度 表现 1 1967 ASCII 美国国家标准学会(American National Standard In ...
- python3.x 基础三:装饰器
装饰器:本质是函数,用于装饰其他函数,在不改变其他函数的调用和代码的前提下,增加新功能 原则: 1.不能修改被装饰函数的源代码 2.不能修改被装饰函数的调用方式 3.装饰函数对于被装饰函数透明 参考如 ...
- python3.x 基础三:函数
1.OOP 面向对象编程,万物皆对象,以class为主,抽象化 2.POP 面向过程变成,万事皆过程,def定义过程 3.函数式编程,将某种功能封装起来,用的时候直接调用函数名,def定义函数,也叫f ...
- python3.x 基础三:set集合
集合,set(),记住: 1个特点:去重,把列表变成集合,达到自动去重操作,无序 5个关系:测试两个列表的交差并子反向差集 方法: | add(...) 常用,已存在元素去重不生效 | A ...
- (代码篇)从基础文件IO说起虚拟内存,内存文件映射,零拷贝
上一篇讲解了基础文件IO的理论发展,这里结合java看看各项理论的具体实现. 传统IO-intsmaze 传统文件IO操作的基础代码如下: FileInputStream in = new FileI ...
- (理论篇)从基础文件IO说起虚拟内存,内存文件映射,零拷贝
为了快速构建项目,使用高性能框架是我的职责,但若不去深究底层的细节会让我失去对技术的热爱. 探究的过程是痛苦并激动的,痛苦在于完全理解甚至要十天半月甚至没有机会去应用,激动在于技术的相同性,新的框架不 ...
- 三、文件IO——系统调用
3.1 文件描述符 文件IO 系统调用是不带缓存的,文件 I/O 系统调用不是 ANSI C 的组成部分,是 POSIX 的组成部分. 系统调用与C库: C库函数的IO 的底层还是调用系统调用 I/O ...
随机推荐
- Python带你做个愉快的"动森"玩家! (超简单代码)
最近Switch上的<动物森友会>可谓是炙手可热,它几乎算是任天堂版的<模拟人生>了,它的最新游戏<集合啦!动物森友会>(以下称“动森”)在发售后,取得了不错的媒体 ...
- ASP.NET Core 找不到 npm指令异常
1.错误再现 利用VS2019预览版创建ASP.NET Core 的单页面Web程序 创建后直接运行,出现如下错误 Ensure that 'npm' is installed and can be ...
- P1886 滑动窗口 单调队列
题目描述 现在有一堆数字共N个数字(N<=10^6),以及一个大小为k的窗口.现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最大值和最小值. 例如: The array i ...
- POJ2389 Bull Math【大数】
Bull Math Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 15040 Accepted: 7737 Descri ...
- Echarts设置点击事件
简单明了. echarts初始化完成之后,给实例对象通过on绑定事件. 这里的事件包括: 'click','dblclick','mousedown','mouseup','mouseover','m ...
- 《LabVIEW 虚拟仪器程序设计从入门到精通(第二版)》一1.3 小结
本节书摘来自异步社区<LabVIEW 虚拟仪器程序设计从入门到精通(第二版)>一书中的第1章,第1.3节,作者 林静 , 林振宇 , 郑福仁,更多章节内容可以访问云栖社区"异步社 ...
- 【10月新版】Aspose.Pdf 10月新版V17.10发布 | 附下载
2019独角兽企业重金招聘Python工程师标准>>> Aspose.Pdf for .NET 17.10 更新 功能和改进 核心 概述 类别 PDFNET-38067 支持DICO ...
- fullpage.js禁止滚动
http://www.wenjiangs.com/doc/fullpage-method 转载于:https://www.cnblogs.com/hzz-/p/8268771.html
- commons-logging slf4j log4j 区别
日志门面 1.Apache通用日志接口(commons-logging.jar) Apache Commons包中的一个,包含了日志功能,必须使用的jar包.这个包本身包含了一个Simple Logg ...
- 【面试题】String类、包装类的不可变性
不可变类的意思是创建该类的实例后,该实例的实例变量是不可改变的.Java提供的8个包装类和String类都是不可变类.因此String和8个包装类都具有不可变性. 就拿String类来说,通过阅读St ...