首页 > 编程语言 > 详细

Python - 文件读写

时间:2018-03-27 15:52:07      阅读:199      评论:0      收藏:0      [点我收藏+]

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 - 文件读写

原文:https://www.cnblogs.com/zhubiao/p/8657648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!