Python open读写文件实现脚本

yipeiwu_com6年前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一次性写入要高。

相关文章

Python实现测试磁盘性能的方法

本文实例讲述了Python实现测试磁盘性能的方法。分享给大家供大家参考。具体如下: 该代码做了如下工作: create 300000 files (512B to 1536B) with...

python分割列表(list)的方法示例

前言 在日常开发中,有些API接口会限制请求的元素个数,这时就需要把一个大列表分割为固定的小列表,再进行相关处理,本文搜集了几个简单的方法,分享出来供大家参考学习,下面来看看详细的介绍:...

Python判断两个list是否是父子集关系的实例

list1 和list2 两个list , 想要得到list1是不是包含 list2 (是不是其子集 ) a = [1,2] b = [1,2,3] c = [0, 1]...

Python使用当前时间、随机数产生一个唯一数字的方法

Python使用当前时间、随机数产生一个唯一数字的方法

本文实例讲述了Python使用当前时间、随机数产生一个唯一数字的方法。分享给大家供大家参考,具体如下: Python生成当前时间很简单,比Java的代码简短多了,Java产生时间可参考《...

基于python实现学生信息管理系统

基于python实现学生信息管理系统

学生信息管理系统负责编辑学生信息,适时地更新学生的资料。下面通过python实现一个简单的学生信息管理系统 stuInfo=[] def main(): while True:...