Python ----读写文件

摘要:

      Python中读写文件还是很方便的,你应该记住的命令如下:

  • close – 关闭文件。跟你编辑器的  文件->保存.. 一个意思
  • read - 读取文件内容。可以把结果赋值给一个变量
  • readline – 读取文本文件中的一行
  • truncate – 清空文件,请小心使用
  • write(stuff) – 将 stuff 写入文件。

一、open

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

 

1 file_object = open('ex1.txt')
2 try:
3     all_the_text = file_object.read()
4 finally:
5     file_object.close()

 

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

 

二、read

  读取文本文件

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

   读取二进制文件

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

    读取所有内容

1 file_object = open('thefile.txt')
2 try:
3      all_the_text = file_object.read( )
4 finally:
5      file_object.close( )

    读取固定字节

1 file_object = open('abinfile', 'rb')
2 try:
3     while True:
4          chunk = file_object.read(100)
5         if not chunk:
6             break
7          do_something_with(chunk)
8 finally:
9      file_object.close( )

    读取每一行

1 list_of_all_the_lines = file_object.readlines( )
2 
3 #如果文件是文本文件,还可以直接遍历文件对象获取每行:
4 
5 for line in file_object:
6      process line

 

三、write

   写文本文件

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

   写二进制文件

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

    追加写文件

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

    写数据

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

    写入多行

1 file_object.writelines(list_of_text_strings)
2 
3 #注:调用writelines写入多行在性能上会比使用write一次性写入要高。

 

posted @ 2016-05-18 21:57  蜡笔小白  阅读(162)  评论(0编辑  收藏  举报