#1、python的IO操作: IO(inputStream、outputStream)输入输出流
全局函数open的使用
若所要查找的文件在当前路径下,可以直接通过open("文件名")
获取;若所要查找的文件不在当前路径下,需要配合os.path.abspath(os.path.curdir)
获取
IO流会返回一个file对象(open函数打开了一个file对象):
file.read(size) #读文件,size默认-1,若不写则默认读到末尾
file.write() #写数据
file.readline() #按行读取字符行
file.flush() #刷新数据
IO中根据输入的内容类型不同分为字节流、字符流
text 文本,字符流
open(path,"tw")
open(path,"tr")
open(path,"ta")
open(path,"tx")
binary 二进制,字节流
open(path,"bw")
open(path,"br")
open(path,"ba")
open(path,"bx")
一般而言,若读取字节文件,建议使用缓存的方式读取,而不要直接读取
1、第一步均是使用open函数完成文件对象的创建(r—读取数据,输入流,从内存到磁盘;w—保存数据,输出流)
文件对象 = open(path,mode) #tw r a x | bw br ba bx
2、操作文件
根据方向分为输入流、输出流
read([size]) #读取内容,表示以size大小读取数据;建议使用size缓存读取数据,防止内存不够
write(content) #输出文件,将文件从内存中保存到磁盘中
3、关闭流
使用file对象的close方法,关闭
open函数的使用
#open函数中第一个参数表示文件,第二个参数表示打开文件的模式,默认为r
f = open("f:\\book1.txt")
#第二步,进行操作
#使用read方法读取数据
msg = f.read()
print(msg)
#最后一步,关闭文件
f.close()
##########################################################################
msg = "hello shuaige,you are an attractive man"
#创建文件对象
#open函数会打开一个文件对象
#open函数中第一个参数表示文件,第二个参数表示打开文件的模式,默认为r,w表示写
f = open("f:\\book1.txt","w")
#第二步,进行操作
#f.write(需要保存的内容)只有当open函数中第二个参数为w时才可使用
f.write(msg)
#最后一步,关闭文件
f.close()
>>>help(open) #help(open)之后看到各个mode代表的含义
========= ===============================================================
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'