python文件操作
文件操作是编程中必不可少的,配置文件,数据存储都是对文件操作。
一、python内置函数open()
1、语法格式:
open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
2、参数
参数encoding为文件编码,仅适用于文本文件。
参数newline为文本模式指定下一行的结束符。可以是None,”,\n,\r,\r\n等。
参数opener用于实现自己定义打开文件方式。
#在Windows操作系统下打开文件,默认使用GBK编码打开, #文本文件的写入utf8编码格式,打开也需要用utf8编码格式。 file=open(‘xx.txt‘,encoding=‘utf8‘) #相对路径 file.read() #打开文件 file.close() #关闭文件
三、文件路径
在windows系统里,文件夹之间用 \ 分隔
‘ b ‘:以二进制形式打开文件。
‘ r+ ‘,‘ w+ ‘:可读可写,很少用
file=open(‘xx.txt‘,‘rb‘) print(file.read()) #二进制读取 b‘\xe5\xa5\xbd\xe5\xa5\xbd\xe5\xad‘ file1=open(‘xx.txt‘,‘wb‘) file1.write(‘好好学习‘.encode(‘utf8‘)) #二进制写入,转成文本
五、文件读取方式
file=open(‘aa.txt‘,encoding=‘utf8‘) file.read() #读取所有数据 file.readline() #读取一行 file.readlines() #读取所有数据,存入列表,每行为一个列表项 file.read(n) #读取n的长度
六、文件拷贝
import os old_file_name=input(‘请输入文件名:‘) if os.path.isfile(old_file_name): names=old_file_name.rpartition(‘.‘) new_file_name=names[0]+‘.bak.‘+names[2] old_file=open(old_file_name,‘rb‘) new_file=open(new_file_name,‘wb‘) while True: content=old_file.read(1024) new_file.write(content) if not content: break new_file.close() old_file.close()
七、将数据写入内存
from io import StringIO s_io=StringIO() print(‘hello ‘,file=s_io,end=‘‘) #控制台不显示 print(‘world!‘,file=s_io) #控制台不显示 print(s_io.getvalue()) #控制台输出‘hello world!‘ s_io.close()
原文:https://www.cnblogs.com/shixiaoxun/p/14495226.html