1.打开文件

  open(name[mode[,buffing])    参数:  文件,模式,缓冲

1)name: 是强制选项,模式和缓冲是可选的

#如果文件不在,会报下面错误
1 >>> f = open(r'D:\text.txt','r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'D:\\text.txt'

2)文件模式

'r'       读模式
'w'   写模式
’a'   追加模式
'b'   二进制模式(可添加到其他模式中使用)
’+'    读/写模式(可添加到其他模块中使用)

NOTE:

    默认的方式,比如说open('filename')是读模式

    r+, 则表示可读写

     如果是二进制文件或图形文件,则必须用缓冲模式

     普通的w模式会覆盖文件的内容,a模式则不会.

     rb则可以用来读取二进制文件.

     通过参数模式中使用U参数,能够在打开文件时使用通用的换行符支持模式,无论\r,\n\r,都会换成\n,而不用考虑运行的平台.

3)缓冲

  0或者False: 无缓冲,所有操作直接针对硬盘

  1或者True:  有缓冲,内存代替硬盘,速度快,只有close,flush才写入硬盘同步.

  > 1  :  表示缓冲区的大小

  -1    :  表示默认的缓冲区大小

2.文件方法

2.1 读写

  #对空文件来说: 提供写时,会在已在字符串末尾追加,

 >>> f = open('somefile.txt','w')
>>> f.write('Hello,')
>>> f.write('World!')
>>> f.close()
#somefile.txt文件内容
Hello,World!

  #对于非空文件:提供w方法时,会覆盖文件中的内容

 >>> f = open('somefile','w')
>>> f.write('This is 1st line.\n')
>>> f.write('This is 2nd line.')
>>> f.close()
#somefile.txt文件内容
This is 1st line.
This is 2nd line.

  简单读取的例子:

 >>> f = open('somefile.txt','r')
>>> f.read(16)#先读取16个字符
'This is 1st line'
>>> f.read() #会读取剩下的内容,除非seek定位到0,重新读取
'.\nThis is 2nd line.'
>>> f.close()

2.2 管道输出

  $ cat somefile.txt | python somescript.py | sort

#一个简单例子: 统计一个文本中单词的数量

$ cat somefile.txt
This is a book!
That is a dog!
Who are you?

  脚本清单:

#somescript.py
import sys
text = sys.stdin.read() #读取所以输入
words = text.split() #分割字符串
print "Word Count:", len(words)

   输出结果:

# cat somefile.txt | python somescript.py
Word Count: 11

  

2.3 读写行

readline :  读取行,包括换行符

readlines:  读取所有行

write:      写一行, 注意:没有writeline方法

writelines: 写多行  

  NOTE: 如何判断不同的行以什么结尾? os.linesep

#UNIX
>>> import os
>>> os.linesep
'\n'
#WINDOWS
>>> import os
>>> os.linesep
'\r\n'

  

2.4 基本文件方法

#测试文本somefile.txt

Welcome to this file

There is nothing here except

This stupid haiku 

#首先读取指定字符 ——  f.read(n)

>>> f = open(r'd:\Learn\Python\somefile.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()

#其次读取所有的行—— f.read()

>>> f = open(r'd:\Learn\Python\somefile.txt','r')
>>> print f.read()
Welcome to this file
There is nothing here except
This stupid haiku   

#接着是读取行 —— f.readline()

>>> f.close()
>>> f = open(r'd:\Learn\Python\somefile.txt')
>>> for i in range(3):
... print str(i) + ':' + f.readline()
...
0:Welcome to this file
1:There is nothing here except
2:This stupid haiku   

#再读取所有行 ——  f.readlines()

>>> import pprint
>>> pprint.pprint(open('somefile.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']

#下面是写文件—— f.write(' ......')

>>> f = open(r'somefile.txt','w')
>>> f.write('this\nis no\nhaiku')
>>> f.close()
运行文件后,内容如下:
this
is no
haiku

#最后是writelines—— f.writelines( ' ....' )

>>> f = open(r'somefile.txt')
>>> lines = f.readlines()
>>> f.close()
>>> lines[1] = "isn't a\n"
>>> f = open('somefile.txt','w')
>>> f.writelines(lines)
>>> f.close()
运行后,文件内容如下:
this
isn't a
haiku  

2.5 关闭文件

  时刻记得close()来关闭文件,这样做的目的:

     安全考虑,防止文件因为某些原因崩溃,写不进数据

    出于数据同步考虑,close(),才会往硬盘中写数据

     出于效率的考虑,内存中的数据可清空一部分出来

  为了确保程序结束时close(),可以用try/finally结合使用

# Open your file here
try:
# Write data to your file
finally:
file.close()

  NOTE: 一般文件在close()之后才会写入硬盘,如果想不执行close()方法,又可以看到写入的内容,那么flush就派上用场了.

3.对文件内容迭代

3.1 按字节处理

def process(string):
print 'Processing...', string
f = open('somefile.txt')
while True:
char = f.read(1)
if not char:
break
process(char)
f.close()

3.2 按行处理

f = open(filename)
while True:
line = f.readline()
if not line:
break
process(line)
f.close()

3.3 读取所有内容

  如果文件不是很大,可以用read(),或者readlines()读取的内容作为字符串来处理.

  #用read来迭代每个字符

f = open(r'D:\Work\Python\somefile.txt')
for char in f.read():
process(char)
f.close()

  #用readlines来迭代行

f = open(r'D:\Work\Python\somefile.txt','r')
for line in f.readlines():
process(line)
f.close()

3.4 使用fileinput懒惰型迭代

  在需要对一个大文件进行迭代时,readlines会占用太多的内存。这个时候可以使用while循环和readline方法来替代。

import fileinput
def process(string):
print 'Processing...', string
for line in fileinput.input('somefile.txt'):
process(line)

  

3.5 文件迭代器

  #Python中文件是可以迭代的

f = open('somefile.txt')
for line in f:
print line,
f.close()

  #如果希望Python来完成关闭的动作,对文件进行迭代,而不使用变量存储变量,代码可以更加精简

for line in open('somefile.txt'):
print line,

  #sys.stdin也是可以迭代的

import sys
for line in sys.stdin:
print line,
运行结果:
D:\Work\Python>python file.py
#输入下面两行
Hello,World!
Hello,Jerry!
^Z
#按下CTRL+Z键后,输入的内容,显示
Hello,World!
Hello,Jerry!

  #可以对文件迭代器执行和普通迭代器相同的操作。比如将它们转换为字符串列表,这样所达到的效果和使用readlines一样.

>>> f = open('somefile.txt','w')
>>> f.write('First line\n')
>>> f.write('Second line\n')
>>> f.write('Third line\n')
>>> f.close()
>>> lines = list(open('somefile.txt'))
>>> lines
['First line\n', 'Second line\n', 'Third line\n']
>>> first,second,third = open('somefile.txt')
>>> first
'First line\n'
>>> second
'Second line\n'
>>> third
'Third line\n'

  

python基础教程总结10——文件的更多相关文章

  1. (Python基础教程之十二)Python读写CSV文件

    Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...

  2. 《python基础教程(第二版)》学习笔记 文件和素材(第11章)

    <python基础教程(第二版)>学习笔记 文件和素材(第11章) 打开文件:open(filename[,mode[,buffering]]) mode是读写文件的模式f=open(r' ...

  3. python基础教程(一)

    之所以选择py交易有以下几点:1.python是胶水语言(跨平台),2.python无所不能(除了底层),3.python编写方便(notepad++等文本编辑器就能搞事情),4.渗透方面很多脚本都是 ...

  4. Python基础教程学习笔记:第一章 基础知识

    Python基础教程 第二版 学习笔记 1.python的每一个语句的后面可以添加分号也可以不添加分号:在一行有多条语句的时候,必须使用分号加以区分 2.查看Python版本号,在Dos窗口中输入“p ...

  5. Python基础教程总结(一)

    引言: 一直都听说Python很强大,以前只是浏览了一些博客,发现有点像数学建模时使用的Matlab,就没有深入去了解了.如今Python使用的地方越来越多,最近又在学习机器学习方面的知识,因此想系统 ...

  6. Python 基础教程之包和类的用法

    Python 基础教程之包和类的用法 建立一个文件夹filePackage 在filePackage 文件夹内创建 __init__.py 有了 __init__.py ,filePackage才算是 ...

  7. 学习参考《Python基础教程(第3版)》中文PDF+英文PDF+源代码

    python基础教程ed3: 基础知识 列表和元组 字符串 字典 流程控制 抽象(参数 作用域 递归) 异常 魔术方法/特性/迭代器 模块/标准库 文件 GUI DB 网络编程 测试 扩展python ...

  8. Python基础教程(第2版 修订版) pdf

    Python基础教程(第2版 修订版) 目录 D11章快速改造:基础知识11.1安装Python11.1.1Windows11.1.2Linux和UNIX31.1.3苹果机(Macintosh)41. ...

  9. (Python基础教程之八)Python中的list操作

    Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...

随机推荐

  1. SQL Server(二)——语句 转

    表的创建: 1.创建列(字段):列名+类型 2.设置主键列(primary key):能够唯一标识一条数据 3.设置唯一(unique):内容不能重复 4.外键关系:一张表(从表)其中的某列引用自另外 ...

  2. 将Angular6自己定义的模块发布成npm包

    创建自己的模块组件 1. ng new 一个工程 2. ng g m 创建模块 例如我这里的modules文件下创建header模块 3. ng g c modules/head 创建一个hear组件 ...

  3. tarjan求割点割边的思考

    这个文章的思路是按照这里来的.这里讨论的都是无向图.应该有向图也差不多. 1.如何求割点 首先来看求割点.割点必须满足去掉其以后,图被分割.tarjan算法考虑了两个: 根节点如果有两颗及以上子树,它 ...

  4. 洛谷P1633 二进制

    P1633 二进制 题目描述 有三个整数A.B.C,以下用N(2)表示N的二进制(没有前导0). 设A(2).B(2).C(2)的最大长度为L,你需要构造三个正整数X.Y.Z,满足以下条件: (1) ...

  5. codevs1051接龙游戏

    1051 接龙游戏  

  6. Whatweb网站指纹信息收集工具

    常规扫描:whatweb www.baidu.com 批量扫描: whatweb -i /root/12.txt 详细回显扫描:whatweb -v www.baidu.com 加强扫描强度:what ...

  7. Nginx 最新版源码编译安装 包含常用模块作用及所需依赖

    第一部分 Nginx最新版源码编译安装 1. 使用的模块 模块1:http_rewrite_module 基于正则匹配来实现重定向.依赖PCRE库,见依赖1 模块2:http_gzip_module ...

  8. 13.组合查询--SQL

    利用UNION操作符将多条SELECT语句组合成一个结果集. 主要有两种情况需要使用组合查询: 在一个查询中从不同的表返回结构数据: 对一个表执行多个查询,按一个查询返回数据. UNION规则 UNI ...

  9. 一行命令将ubuntu升级到最新版本

    zzupdate 是一个开源的命令行程序,通过将几个更新命令组合到一个命令中,使得将 Ubuntu 桌面和服务器版本升级到更新版本的任务变得容易一些. 将 Ubuntu 系统升级到更新的版本并不是一项 ...

  10. 获取所有bean的名字

    import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.facto ...