文件IO操作:
1、操作文件使用的函数是open
2、操作文件的模式:
A、r:读取文件
B、w:往文件里面写内容(前提:先删除文件里面已有的内容)
C、a:是追加(在文件基础上写入新的内容)
D、b;二进制的模式写文件
open函数执行流程:1、open操作文件的时候,他的判断逻辑是:
A、如果是读的模式,文件必须存在
B、如果是写的模式,文件不存在,open内部会自动创建一个文件,然后把内容写进去
操作文件步骤:1,打开文件2,逻辑文件3,关闭文件
def open_w():
#w的模式(写入)
f=open(file='log', mode='w', encoding='utf-8')
f.write('世界你好\nasd')
f.close()
open_w()
def open_a():
#a的模式(追加)
f=open(file='log', mode='a', encoding='utf-8')
f.write('hello')
f.close()
# open_a()
def readFile():
# r的模式(读取)
f=open('log', 'r', encoding='utf-8')
#读取文件所有的内容
#print(f.read())
#读取文件的第一行
#print(f.readline())
#循环读取文件里面的内容:
for item in f.readlines():
print(item.strip())
f.close()
# readFile()
def open_ws():
'''(先读后写)'''
read= open(file='log', mode='r', encoding='utf-8')
write= open(file='log.txt', mode='w', encoding='utf-8')
for item in read.readlines():
write.writelines(item)
read.close()
write.close()
# open_ws()