标签:window 清空 示例 class iso 路径 方式 读写文件 utf-8
一、文件操作
对文件操作的流程
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
"+" 表示可以同时读写某个文件
"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 dream
2、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
总结:打开文件的模式有:
关于可读可写模式:
(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
总结:
"+" 表示可以同时读写某个文件
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
关于 "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处理二进制文件时需标注)
python文件操作 seek(),tell()
seek():移动文件读取指针到指定位置
tell():返回文件读取指针的位置
标签:window 清空 示例 class iso 路径 方式 读写文件 utf-8
原文地址:http://www.cnblogs.com/xuyuanyuan123/p/6670190.html