!/user/bin/python
_*_ coding: utf-8 _*-
文件路径:path......
文件编码:gdk、utf-8......
操作方法:mode读、写、读写、写读、追加、修改.......
关闭close
文件路径前面加r,可以防止转译
文件变量又称文件句柄,最好以f开头f1、file、file_hander、,这样看到f开头的就知道是文件句柄
open()调用的是内置函数,内置函数条用的是系统的open()
一切对文件的操作都是基于文件句柄的操作
光标调整:seek
操作步骤:
打开文件,产生文件句柄
对文件句柄进行操作
绝对路径
s = open("D:\pycharm\python.txt",encoding="utf-8",mode="r")
print(s.read())
s.close()
相对路径
s = open("log1",encoding="utf-8",mode="r")
print(s.read())
s.close()
读:r rb r+ r+b
0:for循环读取,每次读取
s = open("log1",encoding="utf-8",mode="r")
for i in s:
print(i)
s.close()
1:read()全部读取
s = open("log1",encoding="utf-8",mode="r")
print(s.read())
s.close()
2:read(n)读取n个字符
s = open("log1",encoding="utf-8",mode="r")
print(s.read(3))
s.close()
rb读取只能读取三个字节
s = open("log1",mode="rb")
print(s.read(3))
s.close()#打印b'\xe9\xa3\x92'
3:按行读取,加一个readline读取一行
s = open("log1",encoding="utf-8",mode="r")
print(s.readline())
s.close()
4:readlines把读取的内容放在一个列表中,一行就是一个元素
s = open("log1",encoding="utf-8",mode="r")
print(s.readlines())
s.close()
写:w wb w+ w+b
没有文件创建文件写入内容
有文件的花先清空在写入内容
读取文件
f1 = open("log1",encoding="utf-8",mode="w")
print(f1.write("12334"))
f1.close()
图片的读取及写入
f1 = open("pian.jpeg",mode="rb")
content = f1.read()
f2 = open("pain2.jpeg",mode="wb")
f2.write(content)
f1.close()
f2.close()
追加:a ab a+ a+b
没有原文件创建文件写入内容
换行加入在元素前加\n
f1 = open("log3",encoding="utf-8",mode="a")
print(f1.write("\n12334"))
f1.close()
读写模式r+
f1 = open("log3",encoding="utf-8",mode="r+")
print(f1.read())
f1.write("花花")
f1.close()
写读模式w+
f1 = open("log3",encoding="utf-8",mode="w+")
f1.write("中国人")
f1.seek(0)
print(f1.read())
f1.close()
追加读a+
f1 = open("log3",encoding="utf-8",mode="a+")
f1.write("中国人")
f1.seek(0)
print(f1.read())
f1.close()
其他方法:seek任意调整光标位置,tell告诉光标的位置
seek(0)光标在最前,seek(0,2)光标在最后
f1 = open("log3",encoding="utf-8",mode="r")
print(f1.read(6))#读取前两个
print(f1.tell())#光标停留在第6位
with open as不用主动关闭文件句柄,可以操作多个文件句柄
可能会遇到打开同一个文件,第一次文件操作完文件还没关闭,就已经执行下一次文件操作了
with open("log3",encoding="utf-8",mode="r") as f1, \
open("log3"", mode="rb") as f2 :
print(f1.read())
print(f2.read())
文件的改
1以读模式打开源文件
2以写模式打开一个新文件
3将源文件内容按照要求修改,将修改后的内容写入新文件
4删除源文件
5将新文件重命名源文件名
import os#引用OS模块用于删除
with open("file",encoding="utf-8",mode="r") as f1,\#以读模式打开源文件
open("file.bak",encoding="utf-8",mode="w") as f2:#以写模式打开一个新文件
for line in f1:
content = line.replace("yanlong","花花")#将源文件有yanlong的地方全部修改为花花给一个变量
f2.write(content)#将变量的内容写到file.bak当中,在文件句柄没有关闭前都是可以写入的,读一行file内容写一行内容到file.bak中
f1.close()
os.remove("file")
os.rename("file.bak","file")