Python - 文件读写

Posted slynxes

tags:

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

1. 文件读写

1.1 读取文件

1 # read(): Read all context from file
2 fp = open(./data.txt)
3 context = fp.read()
4 fp.close()

 

1.2 read(), readline(), readlines()

read() ,从打开的文件对象中一次性读取所有内容,并返回字符串

readline(),从打开的文件对象中每次读取一行内容,然后读指针跳到下一行,如此完成所有内容的读入

readlines(),从打开的文件对象中一次性读取所有内容,并将内容存储到列表中,列表的一个元素为读入的一行内容

 1 # read(): Read all context from file
 2 fp = open(./data.txt)
 3 context = fp.read()
 4 fp.close()
 5 
 6 # readline(): Read one line at a time from file
 7 fp = open(./data.txt)
 8 context = fp.readline()
 9 fp.close()
10 
11 # readlines(): Read all lines from file and storte in list
12 fp = open(./data.txt)
13 context = fp.readlines()
14 fp.close()

 

1.3 写入文件

write() 将字符串内容写入文件

writelines() 将列表写入文件,列表中的所有元素自动合并

1 # write(): The file writen is string
2 fp = open(./wf.txt,w)
3 fp.write(w, Hello world)
4 fp.close()
5 
6 # writelines(): The file writen is list
7 fp = open(./wf.txt,w)
8 fp.writelines([writelines,hello,world])
9 fp.close()

 

 

1.4 关闭打开的文件句柄

计算机程序中,打开的一个文件占用一个文件句柄,每个进程所拥有的文件句柄数是有限的,并且文件句柄占用计算机资源。所以当我们处理完文件后,需及时关闭文件,在Python中,使用 close() 方法关闭打开的文件,通常使用 try..finally 或者 with..as 语句块来及时关闭处理完的文件对象。

1 # Use finally sure file is closed
2 try:
3     fp = open(./data.txt)
4     context = fp.read()
5 finally:
6     fp.close()

 

1 # Use with sure file is closed
2 with open(./data.txt) as fp:
3     context = fp.read()

 

 

2. 文件读写练习

 

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

python读写文件

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

python常用代码片段总结

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

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

Python文件读写