转载请表明出处:https://www.cnblogs.com/shapeL/p/9141238.html

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

  1. hello
  2. 我们
  3. 326342

1.文件读取

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

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

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

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

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

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

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

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

  1. f = open('../dataconfig/test.json',encoding='utf-8')
  2. data = f.readline()
  3. while data:
  4. print(data)
  5. data = f.readline()
  6. f.close()
  7. 输出结果:
  8. hello
  9.  
  10. 我们
  11.  
  12. 326342

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

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

  1. f = open('../dataconfig/test.json',encoding='utf-8')
  2. data = f.readlines()
  3. print(data)
  4. print(type(data))
  5. for line in data:
  6. print(line.strip())
  7. f.close()
  8. 输出结果:
  9. ['hello\n', '我们\n', '']
  10. <class 'list'>
  11. hello
  12. 我们
  13. 326342

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

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

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

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

  1. f = open('../dataconfig/test.json','w')
  2. f.write('hello,world!')
  3. f.close()

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

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

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

test.json文件内容:

  1. hello
  2. 我们
  3. 326342hello,world!

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

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

  1. try:
  2. f = open('../dataconfig/test.json', 'r')
  3. print(f.read())
  4. finally:
  5. if f:
  6. f.close()

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

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

打开多个文件进行操作:

  1. 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:
  2. for i in f1:
  3. j = f2.readline()
  4. k = f3.readline()
  5. print(i.strip(),j.strip(),k.strip())

python3:文件读写+with open as语句的更多相关文章

  1. python3:文件读写+with open as语句(转)

    读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...

  2. python3 文件读写,编码错误UnicodeDecodeError

    问题:python3 with open文件进行读写,报编码错误 /usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Version ...

  3. Python3 文件读写r,w,a

    # Author;Tsukasa ''' f = open('yesterday','w') #文件句柄...注意open分为‘r’读模式,‘w’写模式(d会先创建文件或者覆盖文件),‘a’为追加模式 ...

  4. python3 文件读写操作中的文件指针seek()使用

    python中可以使用seek()移动文件指针到指定位置,然后读/写.通常配合 r+ .w+.a+ 模式,在此三种模式下,seek指针移动只能从头开始移动,即seek(x,0) . 模式 默认 写方式 ...

  5. Python3 文件读写注意事项(指针问题)

    C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe E:/python/day2/op.py Someho ...

  6. python文件读写,以后就用with open语句

    读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...

  7. Python3:文件读写

    Python3:文件读写 open f = open('filename','r') # 读模式 f = open('filename','w') # 写模式 f = open('filename', ...

  8. Python3 IO编程之文件读写

    读写文件是最常见的IO操作.python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一个,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序终结操作磁盘, ...

  9. python3的文件读写模式

    任何一种语言,文件的读写都是非常常见的.python的文件读写非常简单,仅仅一个函数open(file也可以,但是我不常用). 先看看官网的解释: open(file, mode='r', buffe ...

随机推荐

  1. MVC ---- 如何使用Action委托

    先建立一个Serven 类 public class Seven { public static void TestSeven1() { List<User> userList = Fiv ...

  2. React Native之进度条ProgressViewIOS的使用

    import React,{Component}from 'react'; import { AppRegistry, StyleSheet, Text, View, ProgressViewIOS, ...

  3. 纯CSS实现一个微信logo,需要几个标签?

    博客已迁移至http://lwzhang.github.io. 纯CSS实现一个微信logo并不难,难的是怎样用最少的html标签实现.我一直在想怎样用一个标签就能实现,最后还是没想出来,就只好用两个 ...

  4. TeamViewer 说明截图

  5. Java 常用对象-Math类

    2017-11-02 21:26:18 Math类:Math 类包含用于执行基本数学运算的方法,如初等指数.对数.平方根和三角函数. *属性摘要 *常用方法 random() : 返回[0.0,1.0 ...

  6. C++STL3--queue

    C++STL3--queue 一.心得 STL的这些东西用法都差不多 二.介绍 queue数据结构中的队列 priority_queue优先队列,插入进去的元素都会从大到小排好序 PS:在priori ...

  7. alias和alias_method的区别:

    1.alias 是 Ruby 的一个关键字,因此使用的时候是 alias :new name :oldname,而 alias_method 是 module 类的一个方法,因此使用的时候是 alia ...

  8. FastDFS install

    Version: os: centos7 x64 FastDFS: 5.05 libfastcommon: latest 1. dwonload libfastcommon https://githu ...

  9. Python练习题--持续更新

    1.你是一个高级测试工程师,现在要做性能测试,需要你写一个函数,批量生成一些注册使用的账号. 产生的账号是以@163.com结尾,长度由用户输入,产生多少条也由用户输入,用户名不能重复,用户名必须由大 ...

  10. Leetcode 96

    class Solution { public: int numTrees(int n) { ]; dp[] = ; dp[] = ; dp[] = ; ;i <= n;i++){ ; ;j & ...