open函数
try:
file = open("data.txt",mode='r',encoding="utf8")
c = file.read()
print(c)
file.close()
except Exception as e:
print("打开文件报错:%s"%e)
File常用操作
读全部:read
读一行:readLine
写:write
关闭:close
try:
file = open("data.txt",mode='a+',encoding="utf8")
c = file.readline()
d = file.readline()
file.write("数据分析3班1")
file.write("\n")
file.write("数据分析3班2")
file.close()
except Exception as e:
print("打开文件报错:%s"%e)
with open("data.txt",mode='r',encoding="utf8") as file:
print(file.read())
with写法
异常 + 文件open 合并的写法
with open("data.txt",mode='r',encoding="utf8") as file:
print(file.read())