文件打开和关闭

# 使用open 打开文件,返回时值是一个 File-like对象
f.open('/test/file') # 使用read读取文件
f.read( ) # 使用close关闭文件
f.close( )

读写文件

1. 文件的操作(f.read/f.write)和文件打开方式(f.open)强相关

2. 字符意义:

  • '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)

'r' open for reading (default)

f=open('/test/passwd',mode='r')

# mode=r:可读
f.read() # mode=r:不可写
f.write('test write')
#io.UnsupportedOperation: not writable # mode=r: 文件不存在抛出FileNotFoundError
f=open('/test/not_exist.txt',mode='r')
#FileNotFoundError: [Errno 2] No such file or directory: '/test/not_exist.txt'

'w' open for writing, truncating the file first

# 只要以mode=w方式打开文件,就会清空原文件!
f=open('/test/passwd',mode='w')
#[root@centos1 test]# test -s /test/passwd ;echo $?
#1 # mode=w 不可读f.read()
#io.UnsupportedOperation: not readable # mode=w 可写( 覆盖 > 写 )
f.write('test write\n')
#[root@centos1 test]# cat /test/passwd
#test write # mode=w 打开一个不存在的文件,会创建该文件
f=open('/test/not_exist.txt',mode='w')
#[root@centos1 test]# ls /test/ |grep not_exist.txt
#not_exist.txt

'x' create a new file and open it for writing

# 不能以mode=x打开一个已存在的文件
f=open('/test/passwd',mode='x')
#FileExistsError: [Errno 17] File exists: '/test/passwd' # mode=x 总是创建新文件
f=open('/test/not_exist.txt',mode='x') # mode=x 可写
f.write('test write')
#[root@centos1 test]# cat not_exist.txt
#test write # mode=x 不可读
f.read()
#io.UnsupportedOperation: not readable

'a' open for writing, appending to the end of the file if it exists

f=open('/test/passwd',mode='a')

# mode=a 不可读
f.read()
#io.UnsupportedOperation: not readable # mode=a 可写,且是以追加到文档末尾(>>)的方式,而不是(>)
f.write("zhuijia write")
#[root@centos1 test]# cat passwd
#test write
#zhuijia write # mode=a 不存在的文件就新建
f=open('/test/not_exist.txt',mode='a')
f.write('abc')
#[root@centos1 test]# cat not_exist.txt
#abc

't' text mode (default)   按字符操作

'b' binary mode           按字节操作

# mode=rt,以str方式读取
f=open('/test/passwd',mode='rt')
print(f.read())
#test content
print(type(f.read()))
#<class 'str'> # mode=rb,以bytes方式读取
f=open('/test/passwd',mode='rb')
print(f.read())
#b'test content\n'
print(type(f.read()))
#<class 'bytes'>

# mode=wt,以字符方式写入
f=open('/test/passwd',mode='wt')
print(f.write('测试'))
#2 ——>输出的是字符个数
#[root@centos1 test]# cat passwd
#测试 # mode=wb,必须以bytes方式写入
f=open('/test/passwd',mode='wb')
print(f.write('测试'))
#TypeError: a bytes-like object is required, not 'str'
print(f.write('测试'.encode()))
#6 ——>按字节写入是12个字节

'+' open a disk file for updating (reading and writing)

当mode包含+时, 会增加额外的读写操作, 也就说原来是只读的,会增加可写的操作, 原来是只写的,会增加可读的操作,但是+不改变其他行为

单独的+不能工作, mode里必须有且仅有rwxa中的一个

# 我们可以发现以上的“rwxa”四种打开方式,读和写都不能同时进行
# 且“rwxa”是两两之间是不能同时使用的
f=open("/test/passwd",mode="rw")
#ValueError: must have exactly one of create/read/write/append mode f=open("/test/passwd",mode="r+")
# mode="r+" 可读
print(f.read())
#test content # mdoe="r+" 可写( 追加 >> )
f.write("test2")
print(f.read())
#test content
#test2 f=open("/test/passwd",mode="w+")
# mode="w+" 可读
print(f.read())
#test content # mode="w+" 可写( 覆盖 > )f.write('test2')
print(f.read())
#test2

f=open("/test/passwd",mode="a+")
# mode="a+" 读不报错,但内容为空
print(f.read())
#' ' # mode="a+" 可写
print(f.write('hhh'))
#3

有特定需求的读取操作

#打开二进制文件
with open("/Users/michael/test.jpg",'rb') as f:
print(f.read()) #指定编码打开文件
with open("/Users/gbk.txt",'r',encoding='gbk') as f:
print(f.read()) #含编码不规范的文件打开
with open("/Users/gbk.txt",'r',encoding='gbk',errors='ignore') as f:
print(f.read()) #每次最多读取size()字节内容(常见于大文件读取防止内存爆的情况)
read(size) #按行读取(常用于配置文件)
readlines()

基本的写文件操作

with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')

读写时的指针

当打开文件的时候, 解释器会持有一个指针, 指向文件的某个位置

当我们读写文件的时候,总是从指针处开始向后操作,并且移动指针

f=open("/test/aa")  #默认mode="rt"
print(f.tell())
# #当mode=r时,指针指向0(文件开始)
f.read()
print(f.tell())
#13 f=open("/test/aa",mode="a")
print(f.tell())
# #当mode=a,指针指向EOF(文件末尾)
# seek(cookie, whence=0, /)
cookie:偏移量
whence:可选参数,有3个value可选
*0:从文件开头开始算起
*1:从当前位置开始算起
*2:从文件末尾算起

StringIO和BytesIO

#StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口
#StringIO写
from io import StringIO
f=StringIO()
f.write('hello')
f.write(',')
f.write('world')
print(f.getvalue())
# hello,world #StringIO读
f=StringIO("hello\nhi\nworld")
while True:
s=f.readline()
if s=='':
break
print(s.strip())
# hello
# hi
# world #BytesIO写
from io import BytesIO
f=BytesIO()
f.write('xx'.encode('utf-8'))
print(f.getvalue())
# b'\xe.\xb8\x89\xe.\xb8\x83' ##BytesIO读
import codecs
f=BytesIO('xx'.encode('utf-8'))
print(f.read())
# b'\xe.\xb8\x89\xe.\xb8\x83'

上下文管理

File-like对象

序列化和反序列化

[PY3]——IO——文件读写的更多相关文章

  1. JAVA之IO文件读写

    IO概述:                                                          IO(Input output)流 作用:IO流用来处理设备之间的数据传输 ...

  2. 使用pt-ioprofile监控数据库io文件读写情况

    我们在做IO密集型的应用程序的时候,比如MySQL数据库,通常系统的表现取决于workload的类型. 比如我们要调优,我们就必须非常清楚的知道数据的访问规律,收集到足够的数据,用来做调优的依据. 有 ...

  3. python IO 文件读写

    IO 由于CPU和内存的速度远远高于外设的速度,所以,在IO编程中,就存在速度严重不匹配的问题. 如要把100M的数据写入磁盘,CPU输出100M的数据只需要0.01秒,可是磁盘要接收这100M数据可 ...

  4. NIO与普通IO文件读写性能对比

    最近在熟悉java的nio功能.nio采用了缓冲区的方式进行文件的读写,这一点更接近于OS执行I/O的方式.写了个新旧I/O复制文件的代码,练练手,顺便验证一下两者读写性能的对比,nio是否真的比普通 ...

  5. python学习笔记 IO 文件读写

    读写文件是最常见的IO操作.python内置了读写文件的函数. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统完成的,现代操作系统不允许普通的程序直接对磁盘进行操作,所以, 读写 ...

  6. java IO文件读写例子(OutputStream,InputStream,Writer,Reader)

    一,File创建文件 File file = new File("D:" + File.separator + "yi.txt"); 代码示例: package ...

  7. java io 文件读写操作

    写: import java.io.*; String filePath= "F:\\test.txt"; FileWriter fwriter = null; fwriter = ...

  8. IO文件读写

    *b表示二进制模式访问,但是对于Linux或者Unix系统来说这个模式没有任何意义,因为他们把所有文件都看做二进制文件,包括文本文件 一.三种方法读取文件  方法1:open f=open(" ...

  9. [PY3]——IO——文件目录操作

    IO—os.shutil—文件目录操作 目录操作 1. 新建 os.mkdir(path[, mode]) 相当于mkdir,新建目录 os.makedirs(path[, mode]) 相当于mkd ...

随机推荐

  1. [Elixir005] 查看指定数据的详细信息 i helper

    elixir在1.2后增加了一个新的特性i helper. 在iex shell中使用i可以查看任意数据的数据类型和详细描述 #查看变量描述 iex(1)> i {:test, "Th ...

  2. [.net]ConcurrentBag源码分析

    ConcurrentBag根据操作线程,对不同线程分配不同的队列进行数据操作.这样,每个队列只有一个线程在操作,不会发生并发问题.其内部实现运用了net4.0新加入的ThreadLocal线程本地存储 ...

  3. 记开发个人图书收藏清单小程序开发(五)Web开发

    决定先开发Web端试试. 新增Web应用: 选择ASP.NET Core Web Application,填写好Name和Location,然后点击OK. 注意红框标出来的,基于.NET Core 2 ...

  4. 遇到问题-----cas4.2.x登录成功后报错No principal was found---cas中文乱码问题完美解决

    情况 我们之前已经完成了cas4.2.x登录使用MongoDB验证方式并且自定义了加密. 单点登录(十五)-----实战-----cas4.2.x登录mongodb验证方式实现自定义加密 但是悲剧的是 ...

  5. Ceph 的基础数据结构 [Pool, Image, Snapshot, Clone]

    原文链接:http://www.cnblogs.com/sammyliu/p/4843812.html?utm_source=tuicool&utm_medium=referral 1 Poo ...

  6. 关于Collections的操作方法

    Collections是一个包装类,其中包含有各种有关集合操作的静态多态方,比如可以作用在List和Set上,此类不能实例化. 排序 Integer[] array = new Integer[]{3 ...

  7. element-ui Table表格结合CheckBox实现单选效果

    最近做项目遇到一个需求,需要实现一个表格的单选,由于项目使用的是element-ui.于是去看了表格的文档,确实有单选的方法,但是官方的单选是直接选中表格行,通过颜色来区分 看着效果不明显,实际需要一 ...

  8. AI 的下一个重大挑战:理解语言的细微差别

    简评:人类语言非常博大精妙,同一句话在不同的语境下,就有不同的含义.连人类有时候都不能辨别其中细微的差别,机器能吗?这就是人工智能的下一个巨大挑战:理解语言的细微差别.本文原作者是 Salesforc ...

  9. C语言数据结构之二叉树的实现

    本篇博文是博主在学习C语言算法与数据结构的一些应用代码实例,给出了以二叉链表的形式实现二叉树的相关操作.如创建,遍历(先序,中序后序遍历),求树的深度,树的叶子节点数,左右兄弟,父节点. 代码清单如下 ...

  10. mysql 与sqlser group by

    mysql select * ,count(1)  from simccbillm18 group by MonthNum; SqlSer select  col1,col2 from table g ...