当前位置: 移动技术网 > IT编程>脚本编程>Python > python3:文件读写+with open as语句

python3:文件读写+with open as语句

2018年06月06日  | 移动技术网IT编程  | 我要评论

情欲不羁路,战国游龙将顾问,m壕

前提:文中例子介绍test.json内容:

hello
我们
326342

1.文件读取

(1)打开文件open,默认是已读模式打开文件

f = open('../dataconfig/test.json')
print(f.read())
f.close() 输出结果: hello 鎴戜滑 326342

read():一次性读取文件所有内容

输出结果中出现乱码:需要给open函数传入encoding参数

f = open('../dataconfig/test.json',encoding='utf-8')
print(f.read())
f.close() 输出结果: hello 我们 326342

(2)read(size):读取部分数据

f = open('../dataconfig/test.json',encoding='utf-8')
print(f.read(3))
f.close()
输出结果: hel

(3)redline():每次读取一行数据,逐行读取文件内容

f = open('../dataconfig/test.json',encoding='utf-8')
data = f.readline()
while data:
    print(data)
    data = f.readline()
f.close()
输出结果:
hello

我们

326342

输出结果中每一行数据读取之后都会空一行,解决方案:print(data.strip())或者print(data,end='')

(4)readlines():读取文件所有行

f = open('../dataconfig/test.json',encoding='utf-8')
data = f.readlines()
print(data)
print(type(data))
for line in data:
    print(line.strip())
f.close()
输出结果:
['hello\n', '我们\n', '326342']
<class 'list'>
hello
我们
326342

(5)linecache.getline():读取某个特定行数据

import linecache
data = linecache.getline('../dataconfig/test.json',1)
print(data)
输出结果:
hello

总结:不同场景下读取方式选择

如果文件很小,read()一次性读取最方便
如果不能确定文件大小,反复调用read(size)比较保险
如果是配置文件,调用readlines()最方便;redlines()读取大文件会比较占内存
如果是大文件,调用redline()最方便
如果是特殊需求输出某个文件的n行,调用linecache模块
 
2.文件写入
(1)'w'就是writing,以这种模式打开文件,原来文件中的内容会被新写入的内容覆盖掉,如果文件不存在,会自动创建文件
f = open('../dataconfig/test.json','w')
f.write('hello,world!')
f.close()

test.json文件内容:hello,world!

(2)‘’a’就是appendin:一种写入模式,写入的内容不会覆盖之前的内容,而是添加到文件中

f = open('../dataconfig/test.json','a')
f.write('hello,world!')
f.close()

test.json文件内容:

hello
我们
326342hello,world!

 

3.上述读写文件例子看出,每次读写完之后,都要f.close()关闭文件,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的。

但是实际中,文件读写可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证任何时候都能关闭文件,可以使用try-finally来实现(finally内的代码不管有无异常发生,都会执行)

try:
    f = open('../dataconfig/test.json', 'r')
    print(f.read())
finally:
    if f:
        f.close()

每次都这样写实在是麻烦,python中的with语句用法可以实现

with open('../dataconfig/test.json',encoding='utf-8') as f:
    print(f.read())
输出结果:
hello
我们
326342

打开多个文件进行操作:

with open('../dataconfig/test.json',encoding='utf-8') as f1,open('../dataconfig/test1.json',encoding='utf-8') as f2,open('../dataconfig/test2.json',encoding='utf-8') as f3:
    for i in f1:
        j = f2.readline()
        k = f3.readline()
        print(i.strip(),j.strip(),k.strip())

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网