打开文件的两种方式

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的更多相关文章

  1. Python 基础三 文件 函数

    今天回顾一下之前学的文件操作相关知识点,对于文件的操作,主要有一下几部分构成: 一.文件的基础知识 1.文件操作的基本流程 文件操作其实可以分成三大部分: 1.打开文件,获取文件句柄并赋予一个变量 2 ...

  2. python3【基础】-文件操作

    1. python对文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件操作 关闭文件 现有如下文件: 昨夜寒蛩不住鸣. 惊回千里梦,已三更. 起来独自绕阶行. 人悄悄,帘外月胧明. ...

  3. python3.x 基础三:字符集问题

    总结了一张表,更详细信息百度百科: 序号 年份 编码 标准协会 特点 二进制长度 字符长度 表现 1 1967 ASCII 美国国家标准学会(American National Standard In ...

  4. python3.x 基础三:装饰器

    装饰器:本质是函数,用于装饰其他函数,在不改变其他函数的调用和代码的前提下,增加新功能 原则: 1.不能修改被装饰函数的源代码 2.不能修改被装饰函数的调用方式 3.装饰函数对于被装饰函数透明 参考如 ...

  5. python3.x 基础三:函数

    1.OOP 面向对象编程,万物皆对象,以class为主,抽象化 2.POP 面向过程变成,万事皆过程,def定义过程 3.函数式编程,将某种功能封装起来,用的时候直接调用函数名,def定义函数,也叫f ...

  6. python3.x 基础三:set集合

    集合,set(),记住: 1个特点:去重,把列表变成集合,达到自动去重操作,无序 5个关系:测试两个列表的交差并子反向差集 方法: |  add(...) 常用,已存在元素去重不生效 |      A ...

  7. (代码篇)从基础文件IO说起虚拟内存,内存文件映射,零拷贝

    上一篇讲解了基础文件IO的理论发展,这里结合java看看各项理论的具体实现. 传统IO-intsmaze 传统文件IO操作的基础代码如下: FileInputStream in = new FileI ...

  8. (理论篇)从基础文件IO说起虚拟内存,内存文件映射,零拷贝

    为了快速构建项目,使用高性能框架是我的职责,但若不去深究底层的细节会让我失去对技术的热爱. 探究的过程是痛苦并激动的,痛苦在于完全理解甚至要十天半月甚至没有机会去应用,激动在于技术的相同性,新的框架不 ...

  9. 三、文件IO——系统调用

    3.1 文件描述符 文件IO 系统调用是不带缓存的,文件 I/O 系统调用不是 ANSI C 的组成部分,是 POSIX 的组成部分. 系统调用与C库: C库函数的IO 的底层还是调用系统调用 I/O ...

随机推荐

  1. Qt 正则表达式检查 IP 格式

    KillerSmath 2018年6月29日 下午10:41 @Pranit-Patil Hi there. Like @jonB says above, you should to replace\ ...

  2. IDEA设置导入主题样式皮肤,加入背景图片

    主题下载地址:http://www.riaway.com/theme.php 里面有很多主题,看个人喜好,这里我用的Monokai Sublime Text 3. 导入主题打开IDEA,找到File ...

  3. opencv-6-图像绘制与opencv Line 函数剖析

    opencv-6-图像绘制与opencv Line 函数剖析 opencvc++qt 开始之前 越到后面, 写的越慢, 之前还抽空去看了下 学堂在线那篇文章提供的方法, 博客第一个人评论的我, 想想还 ...

  4. Spring Boot JPA中java 8 的应用

    文章目录 Optional Stream API CompletableFuture Spring Boot JPA中java 8 的应用 上篇文章中我们讲到了如何在Spring Boot中使用JPA ...

  5. dhcpd.conf(5) - Linux man page

    http://linux.die.net/man/5/dhcpd.conf Name dhcpd.conf - dhcpd configuration file Description   The d ...

  6. 美国在线CEO:雅虎被Verizon收购或导致裁员

    北京时间9月13日消息,据外媒报道,AOL首席执行官蒂姆·阿姆斯特朗(Tim Armstrong)称,雅虎.AOL和Verizon整合业务,将导致"部分工作岗位的变化". 阿姆斯特 ...

  7. 前端——Vue-cli 通过UI页面创建项目

    在使用该教程创建项目时请先安装vue ui,具体安装方法请百度 1.打开CMD,输入vue ui 2.点击创建按钮,选择项目目录 3.填写项目名 4.配置项目 选择项目所需要的模块

  8. B. Preparing for Merge Sort

    \(考虑的时候,千万不能按照题目意思一组一组去模拟\) \(要发现每组的最后一个数一定大于下一组的最后一个数\) \(那我们可以把a中的数一个一个填充到vec中\) #include <bits ...

  9. D - 小Z的加油店 线段树+差分+GCD

    D - 小Z的加油店 HYSBZ - 5028   这个题目是一个线段树+差分+GCD 推荐一个差分的博客:https://www.cnblogs.com/cjoierljl/p/8728110.ht ...

  10. zabbix 告警信息与恢复信息

    名称: Action-Email 默认接收人: 故障{TRIGGER.STATUS},服务器:{HOSTNAME1}发生: {TRIGGER.NAME}故障! 默认信息: 告警主机:{HOSTNAME ...