python文件操作
2016-04-13 21:13
423 查看
1.打开文件的模式r : 只读模式打开文件w : 以写模式打开文件,如果该文件存在内容,会直接覆盖a : 以追加的模式打开文件w+:以写读模式打开文件,如果该文件存在内容,会直接覆盖r+:可读写文件rU:可以将\r \n 自动转换成\nrb wb ab:已二进制的方式处理文件2.写操作
>>> f = open("/tmp/test.log","w") >>> f.write("1th\n") 4 >>> f.write("2th\n") 4 >>> f.write("3th\n") 4 >>> f.close() $ more test.log 1th 2th 3th3.读操作
>>> f = open("/tmp/test.log","r") >>> f.read() '1th\n2th\n3th\n' #所有内容读取 >>> f.close() >>> f = open("/tmp_guoxianqi/test.log","r") >>> f.readlines() ['1th\n', '2th\n', '3th\n'] #一行一行读取,成列表格式 >>> f.close()4.追加操作
>>> f = open("/tmp/test.log","a") >>> f.write('append') >>> f.close() $ more test.log 1th 2th 3th append5.打开文件
with open('/tmp_guoxianqi/test.txt','r') as f: print(f.readline().strip())6.close7.fileno8.flush9.read
1)读取3个字符 >>> f.close() >>> f = open('test.log','r') >>> f.read(3) 'asd' >>> f.close()10.readable:是否可读11.readline:读取一行
>>> f = open('test.log','w') >>> f.write("1.sdasddsad\n") 12 >>> f.write("2.sdasddsad\n") 12 >>> f.write("3.sdasddsad\n") 12 >>> f.close() >>> f = open('test.log','r') >>> f.readline() '1.sdasddsad\n' >>> f.readline() '2.sdasddsad\n' >>> f.readline() '3.sdasddsad\n'12.seek:指定文件中的指针位置
>>> f = open('test.log','w') >>> f.write('asdasda') 7 >>> f.close() >>> f = open('test.log','r') >>> f.seek(3) 3 >>> f.read() 'asda' >>> f.close()13.tell查看指针位置
>>> f = open('test.log','w') >>> f.write('asdasda') 7 >>> f.close() >>> f = open('test.log','r') >>> f.tell() 0 >>> f.read(2) 'as' >>> f.tell() 2 >>> f.close()14.truncate:删除指针位置之后的数据15.writeable16.write
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法