open()函数与读写文件

"""读文件"""
# open()函数打开一个文件对象,传入文件名(路径)和标示符(读,写等操作)
# 'r' 标示符标示 '读'
# read()方法一次读取文件的全部内容,用一个str表示
# 最后调用close()方法关闭文件,且必须有close()方法
>>> file = "/tmp/pt.txt"
>>> f = open(file,'r')  
>>> f.read()
'123\n'
>>> f.close()

# 当文件读写产生Error后,后面的f.close()就不会被调用,所以要保证无论是否Error都能正确地关闭文件
# 使用with语句自动调用close()方法

[root@www PythonTest]# cat fileread.py
#!/usr/bin/python3.6
# -*- coding utf-8 -*-
file = "/tmp/pt.txt"
with open(file,'r') as f:
    print(f.read())

# 调用read()会一次性读取文件全部内容,这显然是不实际的,假如文件很大,内存就崩溃了
# read(size)方法每次最多读取size个字节内容。如不能确定文件大小,反复调用read(size)比较合适
# readline()方法每次读取一行内容。
# readlines()方法一次读取所有内容并按行返回list。如果是配置文件,调用readlines()最方便

[root@www PythonTest]# vim fileread.py
#!/usr/bin/python3.6
# -*- coding utf-8 -*-

file = "/tmp/pt.txt"
f = open(file,'r')

for line in f.readlines():
    print(line.strip())  #strip()去除换行符\n
    
f.close()

# 读取二进制文件,例如图片,视频等,使用'rb'模式打开文件
>>> file = "/tmp/test.png"
>>> f = open(file,'rb')
>>> f.read()>>> file = "/tmp/test.png"
# 当读取非utf-8编码的文本文件,需要给open()函数传入encoding参数
>>> f = open(file,'r',encoding='gbk')
# 当遇到编码不规范的文件,可以给open()函数传入errors参数,表示错误后如何处理
>>> f = open(file,'r',encoding='gbk',errors='ignore')  #表示遇到错误忽略


"""写文件"""
# 写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件
# write()方法写入文件
# 最后调用close()方法关闭文件,且必须有close()方法
# 在'w' 模式写入文件时,假如文件存在,会默认使用覆盖的方式
# 如果想使用追加方式使用'a'或'a+'参数.他们都是从文件末尾追加
[root@www PythonTest]# vim filewrite.py
#!/usr/bin/python3.6
# -*- coding utf-8 -*-
file = "/tmp/pt.txt"
f = open(file,'w')  #追加使用f = open(file,'a')
f.write("hello,word\n")
f.close()

"""读写总结"""
open()函数参数
open(filename,mode,bufsize,encoding,errors,newline,closefd)
filename #要打开的文件夹名.例如/tmp/pt.txt
mode     #文件打开的模式,详见下方操作模式列表
bufsize  #缓冲区大小.为0时表示打开文件不用缓冲,为1时表示进行缓冲
encoding #文件编码类型.例如encoding='gbk'
errors   #错误处理方式.例如errors='ignore'
newline  #控制通用换行符模式的行为,不同的os之间的换行符也不一致
closefd()#控制在关闭文件时是否彻底关闭文件

文件操作符(打开模式),操作符可以组合使用
r #只读(默认)
w #可写
a #追加数据
b #二进制数据模式,如图片,视频等
x #新建一个文件并且可写,例如open(file,'x'),在直接使用write()函数写即可
+ #打开文件直接更新
t #文本模式(默认)

文件操作
read()      #
readline()  #读行
readlines() #将整个文件按行读入到列表中
write()     #
writelines()#向文件中写入一个行数据列表
close()     #关闭文件,open()了一个文件就必须close一个文件

使用while语句循环读取文件中的行

#!/usr/bin/python3.6
# -*- coding utf-8 -*-
file = '/tmp/pt.txt'
f = open(file,'r')
while True:
    line = f.readline()
    if not line:
        break
    print(line)
f.close()

使用for循环迭代文件中的所有行
for line in f:
    pass
    
    
处理文件中数据示例:

[root@localhost pythontest]# cat /tmp/pts.txt
1
2
3
[root@localhost pythontest]# cat exampletest.py
#!/usr/bin/python3.6
# -*- coding utf-8 -*-

def file_hd1(name='/tmp/pts.txt'):  #定义一个文件处理函数
    f = open(name)                  #打开文件
    res = 0                         #累加器变量res
    i = 0                           #行数变量i

    for line in f:                  #迭代文件中的行
        i += 1
        print('第%s行的数据为:' % line.strip(),line)
        res += int(line)            #累加每行的数据

    print('这些数的和为:',res)     #打印数据和
    f.close()                       #关闭文件

if __name__ == '__main__':
     file_hd1()                     #调用函数
[root@localhost pythontest]# python3.6 exampletest.py
第1行的数据为: 1

第2行的数据为: 2

第3行的数据为: 3

这些数的和为: 6


"""StringIO"""
 # 有时候,数据读写不一定是文件,也可以在内存中读写
 # "StringIO"的意思就是在内存中读写str
 # StringIO操作的只能是str
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write(' 1')
2
>>> print(f.getvalue())
hello  1
 
# 通过str初始化StringIO,实现以行为单位读取

[root@www PythonTest]# cat fileIO.py
#!/usr/bin/python3.6
# -*- coding utf-8 -*-
from io import StringIO
f = StringIO('hello!\nhi!\nbyebye!')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip())

#输出结果
[root@www PythonTest]# python3.6 fileIO.py
hello!
hi!
byebye!


"""BytesIO"""
# 要操作二进制数据,就需要使用BytesIO
# 写入的不是字符串,而是经过utf-8编码的bytes

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
# 可以用一个bytes初始化BytesIO,然后,像读文件一样读取
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'

 

posted @ 2018-08-30 16:25  畅优植物乳杆菌  阅读(3017)  评论(0编辑  收藏  举报