之前对于Python
打开文件的方法不太清晰,现在来记录一下。
即 直接f = open()
需要手动f.close()
;with open() as f
则不用手动f.close()
FILE_PATH = "./data/text.txt"
def open_file(file_path):
f = open(file_path, "r")
print(f.read())
f.close()
def with_open_file(file_path):
with open(file_path, "r") as f:
print(f.read())
if __name__ == "__main__":
open_file(FILE_PATH)
with_open_file(FILE_PATH)
# 输出结果如下:
# 1
# 23
# 456
# 1
# 23
# 456
猜你喜欢:👇🏻
⭐【Python】break 和 continue 的用法
⭐【Python】格式化print输出,描述在前,变量在后
⭐【Python】find()函数居然还能指定搜索的起点和终点?