Python文件读写常见用法总结

yipeiwu_com6年前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设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python中利用原始套接字进行网络编程的示例

在实验中需要自己构造单独的HTTP数据报文,而使用SOCK_STREAM进行发送数据包,需要进行完整的TCP交互。 因此想使用原始套接字进行编程,直接构造数据包,并在IP层进行发送,即采...

Python小程序之在图片上加入数字的代码

Python小程序之在图片上加入数字的代码

在GitHub上发现一些很有意思的项目,由于本人作为Python的初学者,编程代码能力相对薄弱,为了加强Python的学习,特此利用前辈们的学习知识成果,自己去亲自实现。 来源:Gi...

在Python中如何传递任意数量的实参的示例代码

1 用法 在定义函数时,加上这样一个形参 "*形参名",就可以传递任意数量的实参啦: def make_tags(* tags): '''为书本打标签''' print('标...

python输出电脑上所有的串口名的方法

python输出电脑上所有的串口名的方法

输出电脑上所有的串口名: import serial import serial.tools.list_ports from easygui import * port_list...

连接pandas以及数组转pandas的方法

pandas转数组 np.array(pandas) 数组转pandas pandas.DataFrame(numpy) pandas连接,只是左右接上,不合并值 df...