打开文件
f = open("test_01")
# print(f.read()) #返回全部内容
# print(f.readlines()) #返回每一行内容
print(f.readline()) #返回每一行内容,每次指针下移一行
print(f.readline())
f.close() #每次用完文件需要关闭
写入文件
f = open("test_01", "w")
# f.write("tesstssss") #改写入全部内容
f.writelines(["first\n","second"]) #改写入多行内容
f.close()
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
‘b’ binary mode
什么时候用 b
一般情况下,读写文件是文本格式,用“w”和“r”,当是图片、音频、压缩包等,用“wb”和“rb”。
open 不用关闭的方法(常用)
with open("test_01") as aaa:
print(aaa.read())
with open("test_01", "a") as bbb:
bbb.write("dfkjlafjdkf")
with open("a.png", "rb") as ccc:
with open("c.png","wb") as ddd:
ddd.write(ccc.read())