python学习之二
来源:互联网 发布:c语言数组教程 编辑:程序博客网 时间:2024/06/05 07:28
文件的操作:
打开文件的方式:
>>> open('test.txt', 'w')<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>>>> file('test.txt', 'w')<open file 'test.txt', mode 'w' at 0x2b00cac7e780>>>> f = open ('test.txt', 'w')>>> print f<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>注: w -> 写操作 r->读操作 a-> 文本末尾添加 r+ ->可读可写 b->二进制读写 需要和w r 配合使用 比如:rb wb
读文件操作 :
1. 默认读完
>>> f = open('test1.txt', 'r')>>> f.read()2. 逐行读取文件
>>> f = open('test1.txt', 'r')>>> f.readline()
>>> f=open('test1.txt', 'r')>>> f.readline()'This is the first line in the file.\n'>>> f.readline()'this is the second line in the file.\n'>>> f.readline()'this is the third line in the file.\n'>>> f.readline()'this is the 4th line in the file.\n'>>> f.readline()'this is the 5th line in the file.\n'>>> f.readline()'this is the 6th line in the file.\n'>>> f.readline()'this is the 7th line in the file.\n'>>> f.readline()'this is the 8th line in the file.\n'>>> f.readline()'this is the 9th line in the file.\n'>>> f.readline()'this is the 10th line in the file.\n'>>> f.readline()'\n'>>> f.readline()''3. 读全文,系统自动以‘\n’结尾表示换行,并且每行作为list成员,以逗号分隔!
>>> f = open('test1.txt', 'r')>>> f.readlines()
>>> f=open('test1.txt', 'r')>>> f.readlines()['This is the first line in the file.\n', 'this is the second line in the file.\n', 'this is the third line in the file.\n', 'this is the 4th line in the file.\n', 'this is the 5th line in the file.\n', 'this is the 6th line in the file.\n', 'this is the 7th line in the file.\n', 'this is the 8th line in the file.\n', 'this is the 9th line in the file.\n', 'this is the 10th line in the file.\n', '\n']
for 循环读取文件:
>>> f=open('test1.txt', 'r')>>> for line in f:... print line... This is the first line in the file.this is the second line in the file.this is the third line in the file.this is the 4th line in the file.this is the 5th line in the file.this is the 6th line in the file.this is the 7th line in the file.this is the 8th line in the file.this is the 9th line in the file.this is the 10th line in the file.
以读写方式打开文件,查找偏移量对应的值并读出。
>>> f=open('test2.txt', 'r+')>>> f.write('0123456789\n')>>> f.seek(5)>>> f.read(1)'5'>>> f.seek(-3, 2)>>> f.read(1)'8'
- python学习之二
- Python学习之二
- Python学习系列之二
- python学习笔记之二
- python学习之基础知识(二)
- Python学习之路二
- python学习(二)之编码
- Python学习之Matplotlib (二)
- Python 学习之二:Python超短教程
- Python学习之二【初学Python】
- python之dict学习笔记之二
- Python学习之路之二
- Python学习笔记之二 文本文件合并
- python学习笔记之二---object
- python学习之基础篇二
- 【python学习】之二、函数式编程
- python 学习之二 函数篇
- Python学习之网页抓取(二)
- GrivdView的用存储过程分面效果
- SVN 出现This client is too old to work with working copy...错误
- Java串口通信详解【非常感谢编写这篇文章的兄弟。收益良多】
- 符合推理的解决方法 NSlover
- RTEMS 移植到 sbc2440 的简要笔记
- python学习之二
- Linux下Apache+cgi的配置方法。(转) ---设置cgi-bin
- 觉得一个比较好的AI 神经网络类库AForge neuro
- 24款非常实用的CSS3工具终极收藏
- shell 函数的参数和返回值
- 12款很棒的浏览器兼容性测试工具推荐
- java日期工具类DateUtil-续一
- 我的vimrc配置文件
- HTML 5 标签、属性、事件及浏览器兼容性速查表