一、文件操作
对文件操作的流程
打开文件,得到文件句柄并赋值给一个变量通过句柄对文件进行操作关闭文件打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】w,只写模式【不可读;不存在则创建;存在则清空内容】x, 只写模式【不可读;不存在则创建,存在则报错】a, 追加模式【可读; 不存在则创建;存在则只追加内容】"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】w+,写读【可读,可写】x+ ,写读【可读,可写】a+, 写读【可读,可写】"b"表示以字节的方式操作
rb 或 r+bwb 或 w+bxb 或 w+bab 或 a+b注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
(1)读文件示例:
r:先建一个文件,命名为test1,写入内容为hello world,开始读取文件
a=open ("test1") b=a.read() print(b) a.close()读取的结果是:
hello world(2)写文件示例:“w”和“x”
1、w:先建一个文件,命名为test2,写入内容为welcome to beijing,开始写入内容i have a dream
a=open ("test2",mode="w",encoding="utf-8") b=a.write("i have a dream") print (b) a.close()写入的结果是:(将之前的welcome to beijing给覆盖掉了,所以w写的权限的话,是覆盖之前的内容)
i have a dream2、x:创建了一个空的文件test3,并往里面写入内容为hello world
a=open ("test3",mode="x") b=a.write("hello world") print (b) a.close()写入的结果是:(如果文件存在的话,则会报错,“x”是需要自己创建新的文件)
hello world(3)追加文件示例:
a:先建一个文件,命名为test2,写入内容为i have a dream,追加新内容hello xuyaunyaun
a=open ("test2",mode="a",encoding="utf-8") b=a.write("\nhello xuyuanyuan") print (b) a.close()写入的结果是在后面追加了
i have a dream hello xuyuanyuan
总结:打开文件的模式有:
r,只读模式(默认)。w,只写模式。【不可读;不存在则创建;存在则删除内容;】a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
关于可读可写模式:
(1)r+:新建一个文件test1,写入内容hello,再次写入内容hello xuyuanyuan
a=open ("test1",mode="r+",encoding="utf-8") print(a.read()) b=a.write("\nhello xuyuanyuan") print (b) a.close()写入的结果是在hello后面追加了
hello hello xuyuanyuan(2)w+:新建一个文件test3,写入内容test3,再次写入内容goodgirl
a=open ("test3",mode="w+",encoding="utf-8")print(a.read())b=a.write("goodgirl")a.seek(0)print (a.read())a.close()写入的结果是:(现将之前的test3删除了,再写入了内容goodgirl)注意:read内容是,由于光标此时在内容最后面,没有内容可读,所以需要a.seek(0)将光标移动至最开始的位置,即可read出内容
goodgirl(3)a+:新建一个文件test4,写入内容xuyuanyuan,再次写入内容hello world
a=open ("test4",mode="a+",encoding="utf-8") b=a.write("\nhelloworld") a.seek(0) print(a.read()) a.close()写入的结果是:(在后面追加写入了内容hello world),注意:read内容是,由于光标此时在内容最后面,没有内容可读,所以需要a.seek(0)将光标移动至最开始的位置,即可read出内容
xuyaunyuan helloworld
总结:
"+" 表示可以同时读写某个文件
r+,可读写文件。【可读;可写;可追加】w+,写读a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rUr+U
关于 "b"表示以字节的方式操作:
(1)rb(读权限,以字节的方式):新建一个文件test1,写入内容hello xuyuanyuan
a=open ("test1",mode="rb") print(a.read()) a.close()
打印的结果是:
b'hello xuyuanyuan'
(2)wb+(读写权限,以字节的方式):新建一个文件test2,写入内容welcome to beijing
a=open ("test2",mode="wb+") b=a.write(b"welcome to beijing") a.seek(0) print(a.read()) a.close()打印的结果是:
b'welcome to beijing'(3)ab+(读写权限,追加,以字节的方式):新建一个文件test2,写入内容welcome to beijing,再追加内容welcome xuyuanyuan
a=open ("test2",mode="ab+") b=a.write(b"\nwelcome xuyuanyuan") a.seek(0) print(a.read()) a.close()打印的结果是:
b'welcome to beijing\nwelcome xuyuanyuan'总结:
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
rbwbab
python文件操作 seek(),tell()
seek():移动文件读取指针到指定位置
tell():返回文件读取指针的位置
转载于:https://www.cnblogs.com/xuyuanyuan123/p/6670190.html