python--open/文件操作

来源:互联网 发布:linux 查看自启动服务 编辑:程序博客网 时间:2024/05/22 15:21

open/文件操作

f=open('/tmp/hello','w') #默认为r(只读)

open(路径+文件名,读写模式)

读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

如:’rb’,’wb’,’r+b’等等


打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读; 不存在则创建;存在则只追加内容;】

“+” 表示可以同时读写某个文件

  • r+, 读写【可读,可写,不清空,不创建】
  • w+,写读【可读,可写,会清空,会创建】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写,会追加,会创建】

“b”表示以字节的方式操作

  • rb 或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

注意:

1、使用’W’,文件若存在,首先要清空,然后(重新)创建,

2、使用’a’模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。


  • f.read([size])
    size未指定则返回整个文件,如果文件大小>2倍内存则有问题.f.read()读到文件尾时返回”“(空字串)
  • f.readline()
    返回一行
  • f.readlines([size])
    返回包含size行的列表,size 未指定则返回全部行
  • for line in f: print line
    通过迭代器访问
  • f.write(“hello\n”)
    如果要写入字符串以外的数据,先将他转换为字符串.
  • f.tell()
    返回一个整数,表示当前文件指针的位置(就是到文件头的比特数).
  • f.seek(偏移量,[起始位置])
    用来移动文件指针 偏移量:单位:比特,可正可负 起始位置:0-文件头,默认值;1-当前位置;2-文件尾
  • f.close() #关闭文件
  • f.truncate() #清空文件内容

#!/usr/bin/env python# Filename: using_file.pypoem='''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''f=open('poem.txt','w') # open for 'w'ritingf.write(poem) # write text to filef.close() # close the filef=open('poem.txt')# if no mode is specified, 'r'ead mode is assumed by defaultwhile True:     line=f.readline()     if len(line)==0: # Zero length indicates EOF         break     print line,     # Notice comma to avoid automatic newline added by Pythonf.close()     # close the file
原创粉丝点击