python open 回忆


python open 回忆
2011年05月13日
   python:open/文件操作 open/文件操作
  f=open('/tmp/hello','w')
  #open(路径+文件名,读写模式)
  #读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
  如:'rb','wb','r+b'等等
  f.read([size]) size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回""(空字串)
  file.readline() 返回一行
  file.readline([size]) 返回包含size行的列表,size 未指定则返回全部行
  for line in f: print line #通过迭代器访问
  f.write("hello\n") #如果要写入字符串以外的数据,先将他转换为字符串.
  f.tell() 返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).
  f.seek(偏移量,[起始位置])
  用来移动文件指针
  偏移量:单位:比特,可正可负
  起始位置:0-文件头,默认值;1-当前位置;2-文件尾
  f.close() 关闭文件
  Code:
  #!/usr/bin/env python
  # Filename: using_file.py
  poem='''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''
  f=file('poem.txt','w') # open for 'w'riting
  f.write(poem) # write text to file
  f.close() # close the file
  f=file('poem.txt')
  # if no mode is specified, 'r'ead mode is assumed by default
  while True:
  line=f.readline()
  if len(line)==0: # Zero length indicates EOF
  break
  print line,
  # Notice comma to avoid automatic newline added by Python
  f.close()
  # close the file
  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:
  
  
   whileTrue:
  
  
   chunk =file_object.read(100)
  
  
   ifnot chunk:
  
  
   break
  
  
   do_something_with(chunk)
  
  
  finally:
  
  
   file_object.close( )
  读每行
  
  list_of_all_the_lines = file_object.readlines( )
  如果文件是文本文件,还可以直接遍历文件对象获取每行:
  
  
  forline 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一次性写入要高。
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
  w     以写方式打开 (必要时清空)
  a     以追加模式打开 (从 EOF 开始, 必要时创建新文件)
  r+     以读写模式打开
  w+     以读写模式打开 (参见 w )
  a+     以读写模式打开 (参见 a )
  rb     以二进制读模式打开
  wb     以二进制写模式打开 (参见 w )
  ab     以二进制追加模式打开 (参见 a )
  rb+    以二进制读写模式打开 (参见 r+ )
  wb+    以二进制读写模式打开 (参见 w+ )
  ab+    以二进制读写模式打开 (参见 a+ )
  a.     Python 2.3 中新增

猜你喜欢

转载自wmwi33wmwi.iteye.com/blog/1359749
今日推荐