Python open读写文件实现脚本

yipeiwu_com5年前Python基础

1.open

使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

2.读文件

读文本文件

input = open('data', 'r')
#第二个参数默认为r
input = open('data')

读二进制文件

input = open('data', 'rb')

读取所有内容

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

读固定字节

file_object = open('abinfile', 'rb')
try:
  while True:
    chunk = file_object.read(100)
    if not chunk:
      break
    do_something_with(chunk)
finally:
  file_object.close( )

读每行

list_of_all_the_lines = file_object.readlines( )

如果文件是文本文件,还可以直接遍历文件对象获取每行:

for line in file_object:
    process line

3.写文件

写文本文件

output = open('data', 'w')

写二进制文件

output = open('data', 'wb')

追加写文件

output = open('data', 'w+')

写数据

file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

写入多行

file_object.writelines(list_of_text_strings)

注意,调用writelines写入多行在性能上会比使用write一次性写入要高。

相关文章

python3实现字符串的全排列的方法(无重复字符)

最近在学一些基础的算法,发现我的数学功底太差劲了,特别是大学的这一部分,概率论、线性代数、高数等等,这些大学学的我是忘得一干二净(我当时学的时候也不见得真的懂),导致现在学习算法,非常的...

Python3多线程基础知识点

多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人,比如用户点击了一个按钮去触发某些事件...

python实现把二维列表变为一维列表的方法分析

本文实例讲述了python实现把二维列表变为一维列表的方法。分享给大家供大家参考,具体如下: c = [[1,2,3], [4,5,6], [7,8,9]] 1.用列表推导式...

python 分离文件名和路径以及分离文件名和后缀的方法

分离路径和文件名: os.path.split() 区分文件的名字和后缀: os.path.splitext() import os file_path = "D:/test/t...

Flask中endpoint的理解(小结)

在flask框架中,我们经常会遇到endpoint这个东西,最开始也没法理解这个到底是做什么的。最近正好在研究Flask的源码,也就顺带了解了一下这个endpoint 首先,我们看一个...