博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python天天美味(17) - open读写文件
阅读量:6868 次
发布时间:2019-06-26

本文共 1294 字,大约阅读时间需要 4 分钟。

Python中文件操作可以通过open函数,这的确很像C语言中的fopen。通过open函数获取一个file object,然后调用read(),write()等方法对文件进行读写操作。

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

 

  

  

  

  

  

...

本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/10/1191410.html,如需转载请自行联系原作者

你可能感兴趣的文章
GLSL使用FBO实现MRT(Multiple Render Targets)绘制到多张纹理 【转】
查看>>
诺贝尔文学奖
查看>>
(转)Delphi2009初体验 - 语言篇 - 智能指针(Smart Pointer)的实现
查看>>
分享一个开源的流程图绘制软件--Diagram Designer
查看>>
非典型的scala程序及其编译后的结果
查看>>
Android手势监听类GestureDetector的使用
查看>>
每天学点Python之comprehensions
查看>>
【Dubbo实战】 Dubbo+Zookeeper+Spring整合应用篇-Dubbo基于Zookeeper实现分布式服务(二)...
查看>>
PostgreSQL 配置远程访问
查看>>
Redis之数据存储结构
查看>>
Android 在已有工程中实现微信图片压缩
查看>>
米哈游贺甲:如何实现次世代卡通渲染效果?
查看>>
Javascript继承6:终极继承者----寄生组合式继承
查看>>
【转】xhEditor技术手册 网页编辑器基础教程
查看>>
又添新枕头...
查看>>
卷积的意义【转】
查看>>
用组策略部署Windows防火墙
查看>>
巧用组策略关闭危险端口
查看>>
分布式大规模数据存储 Cloudata
查看>>
BBIT工作感想(二)
查看>>