python学习之文件处理
文件读写
https://www.cnblogs.com/crizygo/p/5369081.html
此处的引用是对相对路径和绝对路径做出解释
1、将文件内容全部读出
f = open('test','w')#打开一个叫做test的文件,w表示写入(write)
f.write("test")#写入字符串“test”
f.write("file")#写入字符串"file"
for i in range(10)
f.write(str(i) + '\n')#写入1到10
f.close()# 关闭文件
f = open('test','r')#使用r读取文件(read) 无论是对文件进行读取还是写入,首先都要打开文件
text = f.read()#使用read方法进行读取()
f.close()
print(text)
得到结果如下:
testfile
0
1
2
3
4
5
6
7
8
9
2.读取文件中的一行
f = open('test','r')#使用了r读取文件(read)
text = f.readline()#使用readline方法读取文件的一行
text1 = f.readline()#接着进行读取
print(text)
print(text1)
f.close()
得到结果如下:
testfile
0
3.读取文件的每一行并放回列表形式
f = open('test'.'r')#使用r读取文件(read)
text = f.readlines()#使用readlines方法读取文件的每一行,放到列表中,并返回
f.close()
print(text)
得到的结果如下:
['testfile\n', '0\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n']#将换行符一同读取
在文件读写过程中如果出现bug,f.close()就很可能不被执行,这样会造成系统资源浪费,并且可以打开的文件数量有限,所以我们会用到try…finally
try:
f = open('test','r')
text = f.readlines()
1 / 0
finally:
if f:
f.close()
虽然这种写法会报错,但是最终文件是被关闭的
另一种方法:
with open('test','r') as f:
test = f.read()
print(test)
print("Is the file closed?",f.closed)
1 / 0
得到的结果如下:
testfile
0
1
2
3
4
5
6
7
8
9
Is the file closed? False
两种写法的区别在于简洁度
over
————————————————
版权声明:本文为CSDN博主「m0_44970284」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_44970284/article/details/107589743