Python笔记之 - 一张截图诠释"文件读写" !
源代码如下:
# 文件读写 str_test1 = "先创建txt文件再写入内容: 我是大帅哥"
# with open("file_path.xxx", "w") as f 语句会先创建一个xxx格式的文件并以只写方式打开 ,
# 再往文件里面写入内容(以只写方式会覆盖原内容), 而且这种语句的好处是不用再在末尾调用.close()关闭文件.
with open("./file.txt","w") as f:
f.write(str_test1) str_test2 = ", 我是大美女!"
with open("./file.txt","a") as f: # "a"是以追加的方式打开文件
f.write(str_test2) with open("./file.txt","r") as f: # "r"是以只读方式打开文件
print(f.read()) str_test3 = "先创建html文件再写入内容: 嘿嘿!"
with open("./new_file.html","w") as f: # 创建html文件并以只写方式打开该文件
f.write(str_test3) with open("./new_file.html","r") as f:
print(f.read())