python语言open用法
2017-09-17 11:05
405 查看
open/文件操作
f=open('/tmp/hello','w')
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
如:'rb','wb','r+b'等等
读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
注意:
1、使用'W',文件若存在,首先要清空,然后(重新)创建,
2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。
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:
f=open('/tmp/hello','w')
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
如:'rb','wb','r+b'等等
读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
注意:
1、使用'W',文件若存在,首先要清空,然后(重新)创建,
2、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。
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 |
相关文章推荐
- 详解Python中open()函数指定文件打开方式的用法
- ubuntu14.04LTS下编译安装Open Babel和python语言绑定
- Python语言学习:Beautiful Soup四个对象的具体用法
- python 语言中with as 的用法
- 有关break的用法多种语言(C,C++,Java,C#,Python)
- python语言是动态语言、给类添加属性、方法、静态方法和类方法、__slots__()、python中的生成器、yield的用法
- Python语言学习:Beautiful Soup四个对象的具体用法
- python语言是动态语言、给类添加属性、方法、静态方法和类方法、__slots__()、python中的生成器、yield的用法
- 在使用python语言的open函数时,提示错误OSError: [Errno 22] Invalid argument: ‘文件路径’
- C语言文件操作函数open、write用法速记
- Python语言——Pandas包中的get_dummy()函数用法
- 详解Python中open()函数指定文件打开方式的用法
- python语言中with as的用法使用详解
- python robotframework用法及"wxpython not found"和“no browser is open”问题解决
- Python语言学习---结构的用法
- Python - 编程 (流程控制) 区别C 和我知道语言的用法
- python 语言常见用法积累
- python语言else的用法
- Python open()用法
- python语言_open()文件操作