文件的增,增加。写入内容,文件.write()。例如:
file_name =‘demo.txt’
with open(file_name,‘w’,encoding=‘utf-8’)as file_obj:#encoding='utf-8’写入的是纯文本
‘w’:w写入文件时,如果文件不存在则会创建一个文件。如果文件存在则会覆盖原文件内容
‘r’:只能读取
‘a’:追加写入
file_obj.write(‘鼓角揭天嘉气冷,风涛动地海山秋’)
文件的关闭文件.close()
file_name =‘demo.txt’
file_obj=open(file_name)
file_obj.close()
content=file_obj.read()
print(content)
with…as…自带关闭
file_name= ‘demo.txt’
with open(file_name,‘rb’)as file_obj:
file_obj.read()
print(file_obj)
文件的打开调用open()方法。例如:
file_name =‘demo.txt’
file_obj =open(file_name)#文件调用open()方式打开的过程中,会出现一个返回值,所以定义一个变量
print(file_obj)
文件读取方式调用read()
file_name =‘demo.txt’
file_obj =open(file_name)#先打开文件,然后进行读取
file_obj.close()#关闭之后再进行读取,则报错,关闭成功
content =file_obj.read()
print(content)