Python文件读写常见用法总结

yipeiwu_com7年前Python基础

1. 读取文件

# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
文件读取三步骤:
  1.打开文件
    f=open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
      mode: r,w,a,b,+
  2.操作文件
    f.read(),把整个文件读入单一字符串
    f.read(N),读取之后的N个字节
    f.readlines(),读取整个文件到字符串列表
    f.readline(),读取下一行
  3.关闭文件
    f.close()
  f.seek(offset),移动文件指针位置
  f.flush(),把缓冲区数据刷到硬盘中
"""
f=open('吻别.txt',encoding='utf-8')
print(f)
data=f.read()
# data=f.readlines()
print(data)
f.close()

2. 写入文件

"""
文件写入三步骤:
  1.打开文件
  2.操作文件
    f.write()
    f.writelines(aList),把列表中所有的字符串写入文件
  3.关闭文件
"""
f=open('test.txt',mode='w',encoding='utf-8')
f.write('line01\n')
f.write('line02\n')
f.close()

3. 文件也是迭代器

# !/usr/bin/env python
# -*- coding:utf-8 -*-
from collections import Iterable
try:
  f=open('吻别.txt',mode='r',encoding='utf-8')
  print(isinstance(f, Iterable)) # True,文件也是迭代器类型
  for line in f:
    print(line,end='')
finally:
  f.close()

4. 使用上下文管理器自动关闭文件

with open('test.txt',mode='w',encoding='utf-8') as f:
  f.write('line01\nline02\n')
with open('test.txt') as f:
  data = f.read()
  print(data)

5. 读写二进制文件

with open('美猴王.jpg',mode='rb') as fin,open('美猴王_copy.jpg',mode='wb') as fout:
  data=fin.read()
  fout.write(data)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

pandas 对日期类型数据的处理方法详解

pandas 对日期类型数据的处理方法详解

pandas 的日期/时间类型有如下几种: Concept Scalar Class Array Class panda...

在Python中使用turtle绘制多个同心圆示例

在Python中使用turtle绘制多个同心圆示例

我就废话不多说了,直接上代码吧! import turtle t = turtle.Pen() my_colors = ("red","green","yellow","black"...

Python+selenium实现截图图片并保存截取的图片

这篇文章介绍如何利用Selenium的方法进行截图,在测试过程中,是有必要截图,特别是遇到错误的时候进行截图。在selenium for Python中主要有三个截图方法,我们挑选其中最...

Python3中的2to3转换工具使用示例

python3与python2的还是有诸多的不同,比如说在2中: 复制代码 代码如下: print "Hello,World!"  raw_input()  在...

基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解

基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解

Pyplot matplotlib.pyplot是一个命令型函数集合,它可以让我们像使用MATLAB一样使用matplotlib。pyplot中的每一个函数都会对画布图像作出相应的改变,...