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

转载请代表出处:http://www.javashuo.com/article/p-sursppms-hu.htmlhtml

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

hello
咱们
326342

1.文件读取json

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

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

read():一次性读取文件全部内容函数

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

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():每次读取一行数据,逐行读取文件内容code

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='')htm

(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())
相关文章
相关标签/搜索