Python文件读写

Posted 傅余生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python文件读写相关的知识,希望对你有一定的参考价值。

Python读文件

方法一:open()创建文件对象  .read()方法读文件 .close()关闭文件对象

file_object = open("2.txt") #open()创建文件对象
contents = file_object.readlines()
print(contents)
file_object.close()#文件使用完毕后必须关闭,因为文件对象会占用操作系统资源

 

方法二:通过with open语句 由于文件使用完毕后必须关门,Python引入了with open自动调用close()方法

file  = "2.txt"
with open(file) as file_oj:
    contents = file_oj.readlines() #readlines()返回以列表格式的全部文件内容  readline返回文件每一行内容
    print(contents)

 

Python写文件

with open(file,‘w‘) as file_oj: #同样使用with open语句 ‘w‘代表文件写入 
file_oj.write("i love python
")
file_oj.write("i love mysql
")

 

with open(file,‘a‘) as file_oj: #‘a‘代表以追加的方式写入内容
file_oj.write("i love you
")

 

2020-03-20 16:40

以上是关于Python文件读写的主要内容,如果未能解决你的问题,请参考以下文章

python读写文件

Python代码中打开txt文件(非读写)

python常用代码片段总结

我在哪里更改此 Python 代码片段以将临时文件保存在 tmp 文件夹中?

常用python日期日志获取内容循环的代码片段

Python文件读写