Flow:
1, open file
file handle = open (filename, mode, encoding)
open mode of the file has:
a basic Open:
1) R & lt: read-only [Default]
f = open ( "file.txt "," R & lt ")
Data reached, f.read = ()
f.close ()
Print (Data)
2) W: write only mode [unreadable; file does not exist it is created, empty the contents exist]
f = open (" file1 .txt "," w ")
f.write (" 123456789 ")
f.close ()
3) the X-: [write-only mode unreadable; file does not exist it is created, then there is an error]
f = open (" file1.txt "," X ")
f.write (" 123456789 ")
f.close ()
. 4) A: append mode [unreadable; file does not exist it is created, only the presence of the additional content]
f = open (" file1.txt " , "A")
f.write ( "asdfghjk")
F.close ()
Second, the byte opened:
. 1) RB: read-only,
f = open("file1.txt","rb")
data = f.read()
f.close()
str_data = str(data, encoding="utf-8")
print(str_data)
2)wb:只写
f = open("file1.txt","wb")
str_data = "中国人"
byte_data = byte(str_data, encoding="utf-8"
data = f.write(byte_data)
f.close()
“+” 表示可以同时读写某个文件
1)r+:读写【可读,可写】注意:1)可写时,末尾追加,指针在最后。2)从开始向后读
f = open("file1.txt","r+", encoding="utf-8")
#指针为0,起始位置
print(f.tell()) #获取指针的位置
data = f.read() #先读取
print(data)
f.write("法国人") #再写
f.seek(0) #将指针放到最前
data = f.read() #最后再读取
print(data)
f.close()
2)w+:写读【可读,可写】注意:1)先清空,在写后,就可读了;写,指针在最后。2)从开始向后读
f = open("file1.txt","w+", encoding="utf-8")
f.write("赵钱孙李")a
f.seek(0) #将指针放到最前
data = f.read()
f.close()
print(data)
3)x+:写读【可读,可写】 注意:如果文件存在,则报错。
4)a+:写读【可读,可写】注意:打开的同时,指针已经到最后了;
f = open("file1.txt","a+", encoding="utf-8")
data = f.read()
print(data) #没有读到数据
f.seek(0) #将指针放到最前
data = f.read()
f.close()
print(data)
2、操作文件
1)close():关闭文件
2)fileno():文件描述符
3)flush():将内存的数据写入硬盘
4)readline():仅读一行数据
5)seek():获取指针位置
6)truncate():截取数据,依赖于指针的位置开始截取数据
7)read():读取数据
8)write():写入数据
3、关闭文件
with open(文件名,模式) as f: 等价于 f.close()