文件操作

python可以对文件进行查看,创建等功能,可以对文件内容进行添加,修改,删除,且所使用到的函数在python3.5.x中为open,在python2.7.x中同时支持fileopen,但是在3.5.x系列移除了file函数

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

python文件打开方式

f = open('1.txt') # 打开文件
# 文件句柄 = open('文件路径','打开模式')

first_line = f.readline() # 读一行, 并赋值
print('first line:', first_line)
data = f.read() # 读取剩下的所有内容, 文件大时不要使用
print(data) # 打印内容

f.close() # 关闭文件
ps:文件句柄相当于变量名,文件路径可以写为绝对路径也可以写为相对路径

python打开文件的模式

基本的模式

模式 说明 注意事项
r 只读模式 文件必须存在
w 只写模式 文件不存在则创建文件,文件存在则清空文件内容
x 只写模式 文件不可读,文件不存在则创建,存在则报错
a 追加模式 文件不存在创建文件,文件存在则在文件末尾添加内容

+的模式

模式 说明
r+ 读写
w+ 写读
x+ 写读
a+ 写读

b的模式

模式 说明
rb 二进制读模式
wb 二进制写模式
xb 二进制只写模式
ab 二进制追加模式
提示:以b方式打开文件时,读取到内容是字节类型,写入时也需要提供字节类型

+b的模式

模式 说明
rb+ 二进制读写模式
wb+ 二进制读写模式
xb+ 二进制只写模式
ab+ 二进制读写模式

python文件读取方式

模式 说明
read([size]) 读取文件全部内容,如果设置了size,那么就读取size字节
readline([size]) 一行一行的读取
readlines() 读取到的每一行内容作为列表中的一个元素

测试文件名是hello.txt ,文件内容为:

Hello Word!
123
abc
456
abc
789
abc

read

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# 以只读的方式打开文件hello.txt
f = open("hello.txt","r")
# 读取文件内容赋值给变量c
c = f.read()
# 关闭文件
f.close
# 输出c的值
print(c)

输出结果

➜  python_test python3 013-exercise-1-read.py
Hello Word!
123
abc
456
abc
789
abc

readline

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# 以只读模式打开文件hello.txt
f = open("hello.txt","r")
# 读取第一行
c1 = f.readline()
# 读取第二行
c2 = f.readline()
# 读取第三行
c3 = f.readline()
# 关闭文件
f.close()
# 输出读取文件第一行内容
print(c1)
# 输出读取文件第二行内容
print(c2)
# 输出读取文件第三行内容
print(c3)

执行结果

➜  python_test python3 013-exercise-2-readline.py
Hello Word!

123

abc

readlines

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

f = open("hello.txt","r")
c = f.readlines()
print(type(c))
f.close()
for n in c:
    print(n)

执行结果

➜  python_test python3 013-exercise-3-readlines.py
<class 'list'>
Hello Word!

123

abc

456

abc

789

abc

python文件写入方式

write

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

# 以只写的模式打开文件write.txt,没有则创建,有则覆盖内容
file = open("write.txt","w")
# 向文件中写入内容
file.write("test write")
# 关闭文件
file.close()

write.txt文件内容

➜  python_test python3 013-exercise-4-write.py
➜  python_test cat write.txt
test write

writelines

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

f = open("wr_lines.txt","w",encoding="utf-8")
f.writelines(["11","22","33"])
f.close

wr_lines.txt文件内容

➜  python_test python3 013-exercise-5-writelines.py
➜  python_test cat wr_lines.txt
112233

python文件操作所提供的方法

close(self)

关闭已经打开的文件

f.close()

fileno(self)

文件描述符

>>> f = open("hello.txt","r")
>>> ret = f.fileno()
>>> f.close()
>>> print(ret)
3

flush(self)

刷新缓冲区的内容到硬盘中

f.flush()

isatty(self)

判断文件是否是tty设备,如果是tty设备则返回True,否则返回False

>>> f = open("hello.txt","r")
>>> ret = f.isatty()
>>> f.close()
>>> print(ret)
False

readable(self)

是否可读,如果可读返回True,否则返回False

>>> f = open("hello.txt","r")
>>> ret = f.readable()
>>> f.close()
>>> print(ret)
True

readline(self,limit=-1)

每次仅读一行数据

>>> f = open("hello.txt","r")
>>> print(f.readline())
Hello Word!

>>> print(f.readline())
123

>>> f.close()

readlines(self,hint=-1)

把每一行内容当做列表中的一个元素

>>> f = open("hello.txt","r")
>>> print(f.readlines())
['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'abc\n']
>>> f.close()

tell(self)

获取指针位置

>>> f = open("hello.txt","r")
>>> print(f.tell())
0
>>> f.close()

seek(self,offset,whence=io.SEEK_SET)

指定文件中指针位置

>>> f = open("hello.txt","r")
>>> print(f.tell())
0
>>> f.seek(3)
3
>>> print(f.tell())
3
>>> f.close()

seekable(self)

指针是否可操作

>>> f = open("hello.txt","r")
>>> print(f.seekable())
True
>>> f.close()

writable(self)

是否可写

>>> f = open("hello.txt","r")
>>> print(f.writable())
False
>>> f.close()

writelines(self,lines)

写入文件的字符串序列,序列可以是任何迭代的对象字符串生产,通常是一个字符串列表

>>> f = open("wr_lines.txt","w")
>>> f.writelines(["11","22","33"])
>>> f.close()

read(self,n=None)

读取指定字节数据,后面不加参数默认读取全部

>>> f = open("wr_lines.txt","r")
>>> print(f.read(3))
112
>>> f.seek(0)
0
>>> print(f.read())
112233
>>> f.close()

write(self,s)

往文件里面写内容

>>> f = open("wr_lines.txt","w")
>>> f.write("abcdef")
6
>>> f.close()

文件内容

➜  python_test cat wr_lines.txt
abcdef

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即

with open('log','r') as f:
    代码块

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源

在python2.7及以后,with又支持同时对多个文件的上下文管理,即

with open('log1') as obj1, open('log2') as obj2:
    pass