<<Python基础教程>>学习笔记 | 第11章 | 文件和素材
打开文件
open(name[mode[,buffing])
name: 是强制选项,模式和缓冲是可选的
#假设文件不在。会报以下错误:
>>> 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'
文件模式
NOTE:
1. 默认的方式,比方说open('filename')是读模式
2. r+, 则表示可读写
3. 假设是二进制文件或图形文件,则必须用缓冲模式
4. 普通的w模式会覆盖文件的内容,a模式则不会.
5. rb则能够用来读取二进制文件.
6, 通过參数模式中使用U參数,可以在打开文件时使用通用的换行符支持模式,不管\r,\n\r,都会换成\n。而不用考虑执行的平台.
缓冲:
第三个參数。可选
0或者False: 无缓冲。全部操作直接针对硬盘
1或者True: 有缓冲,内存取代硬盘,速度快,仅仅有close,flush才写入硬盘同步.
> 1 : 表示缓冲区的大小
-1 : 表示默认的缓冲区大小
基本文件方法
NOTE: 类文件对象是支持一些文件的方法的对象,比方file方法。最重要的两个方法,read,write方法.还有urllib.urlopen返回对象,他们支持的方法有: read,readline,readlines
三种标准的流
sys.stdin :标准输入流,可通过输入或者使用管道把它和其他程序的标准输出链接起来提供文本
sys.stdout :放置input,raw_input写入的数据,可在屏幕上显示,也可通过|连接到其他程序的标准输入
sys.stderr :错误信息,比方说栈追踪被写入sys.stderr.
读和写
最重要的能力是提供读写
#对空文件来说: 提供写时。会在已在字符串末尾追加,
>>> 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()
管道输出
$ 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
随机訪问:
用seek和tell来訪问自己感兴趣的部分
seek(offset[,whence]). offset,偏移量,Whence值
0: 開始位置
1: 当前位置
2: 文件末尾
简单样例:
>>> f = open('somefile.txt','w')
>>> f.write('01234567890123456789')
>>> f.seek(5)
>>> f.write('Hello,World!')
>>> f.close()
>>> f = open('somefile.txt')
>>> f.read()
'01234Hello,World!789'
#用tell来返回当前文件的位置
>>> f = open('somefile.txt')
>>> f.read(3)
'012'
>>> f.read(2)
'34'
>>> f.tell()
5L
读写行:
readline : 读取行,包含换行符
readlines: 读取全部行
write: 写一行, 注意:没有writeline方法
writelines: 写多行
NOTE: 怎样推断不同的行以什么结尾? os.linesep
#UNIX
>>> import os
>>> os.linesep
'\n'
#WINDOWS
>>> import os
>>> os.linesep
'\r\n'
关闭文件
时刻记得close()来关闭文件,这样做的目的:
1. 出于安全考虑,防止文件由于某些原因崩溃。写不进数据
2. 出于数据同步考虑,close(),才会往硬盘中写数据
3. 出于效率的考虑,内存中的数据可清空一部分出来
为了确保程序结束时close(),能够用try/finally结合使用
# Open your file here
try:
# Write data to your file
finally:
file.close()
NOTE: 一般文件在close()之后才会写入硬盘,假设想不运行close()方法。又能够看到写入的内容,那么flush就派上用场了.
使用基本方法:
#測试文本somefile.txt
Welcome to this file
There is nothing here except
This stupid haiku
首先读取指定字符
>>> f = open(r'd:\Learn\Python\somefile.txt')
>>> f.read(7)
'Welcome'
>>> f.read(4)
' to '
>>> f.close()
其次读取全部的行
>>> 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.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
再读取全部行:
>>> import pprint
>>> pprint.pprint(open('somefile.txt').readlines())
['Welcome to this file\n',
'There is nothing here except\n',
'This stupid haiku']
以下是写文件
>>> f = open(r'somefile.txt','w')
>>> f.write('this\nis no\nhaiku')
>>> f.close()
执行文件后,内容例如以下:
this
is no
haiku
最后是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
对文件内容进行迭代
主要的方法如: read,readline,readlines,还有xreadline和文件迭代器
以下的样例都使用的虚拟函数process(),表示每一个字符或每行处理过程
def process(string):
print 'Processing', string
更实用的实现是:在数据结构中存储数据。计算和值。
用re模块来替代模式或者添加行号.假设要实现上面的功能。
则应该讲filename变量设置为实际的文件名称.
按字节处理
def process(string):
print 'Processing...', string
f = open('somefile.txt')
char = f.read(1)
while char:
process(char)
char = f.read(1)
f.close()
代码重用一般是件坏事,懒惰是美德。重写下代码例如以下:
def process(string):
print 'Processing...', string
f = open('somefile.txt')
while True:
char = f.read(1)
if not char:
break
process(char)
f.close()
NOTE: 这样写就比上面要好,避免了反复的代码.
按行操作
f = open(filename)
while True:
line = f.readline()
if not line:
break
process(line)
f.close()
读取全部内容
假设文件不是非常大,能够用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()
使用fileinput实现懒惰行迭代
在须要对一个大文件进行迭代时。readlines会占用太多的内存。
这个时候能够使用while循环和readline方法来替代。
import fileinput def process(string):
print 'Processing...', string for line in fileinput.input('somefile.txt'):
process(line)
文件迭代器
#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'
NOTE:
1.用序列来做解包操作很使用
2.读文件操作时,能够不用close()
WITH语句的使用
with语句使用所谓的上下文管理器对代码块进行包装。同意上下文管理器实现一些设置和清理操作。
比如:文件能够作为上下文管理器使用,它们能够关闭自身作为清理的一部分。
NOTE:在PYTHON2.5中,须要使用from __future__ import with_statement进行with语句的导入
with open('test.txt') as myfile:
while True:
line = myfile.readline()
if not line:
break
print line,
#假设这样写的话。就无需关闭文件了。
------
本章新函数
file(name[,mode[,buffering]]) 打开一个文件并返回一个文件对象
open(name[,mode[,buffering]]) file的别名;在打开文件,使用open而不是file
<<Python基础教程>>学习笔记 | 第11章 | 文件和素材的更多相关文章
- <<Python基础教程>>学习笔记 | 第10章 | 充电时刻
第10章 | 充电时刻 本章主要介绍模块及其工作机制 ------ 模块 >>> import math >>> math.sin(0) 0.0 模块是程序 一个简 ...
- <<Python基础教程>>学习笔记 | 第04章 | 字典
第04章:字典 当索引不好用时 Python唯一的内建的映射类型,无序,但都存储在一个特定的键中.键能够使字符.数字.或者是元祖. ------ 字典使用: 表征游戏棋盘的状态,每一个键都是由坐标值组 ...
- <<Python基础教程>>学习笔记 | 第12章 | 图形用户界面
Python支持的工具包非常多.但没有一个被觉得标准的工具包.用户选择的自由度大些.本章主要介绍最成熟的跨平台工具包wxPython.官方文档: http://wxpython.org/ ------ ...
- 《Python基础教程(第二版)》学习笔记 -> 第十一章 文件和素材
打开文件 open函数用来打开文件,语句如下: open(name[,mode[,buffering]]) open函数使用一个文件名作为唯一的强制参数,然后后返回一个文件对象.模式(mode)和缓冲 ...
- <<Python基础课程>>学习笔记 | 文章13章 | 数据库支持
备注:本章介绍了比较简单,只是比较使用样品,主要假设是把握连接,利用数据库.和SQLite做演示样本 ------ Python数据库API 为了解决Python中各种数据库模块间的兼容问题,如今已经 ...
- Python基础教程(第3版) 笔记(三)
1.9.1让脚本像普通程序一样在UNIX中运行脚本,只需将下面的代码作为脚本的第一行, 就可在UNIX中轻松运行脚本: #!/usr/bin/env python 要像普通程序一样运行脚本,还必须将其 ...
- Python基础教程(第3版) 笔记(二)
1.8模块Python提供了完成(某人的年 龄为32.9,并想将这个值向下圆整为32,因为他还没有满33岁)这种任务的函 数floor.导入模块,可以使用特殊命令import.函数floor包含在模块 ...
- Python基础教程(第3版) 笔记(一)
1.1 数和表达式: 除法运算的结果为小数,即浮点数 >>>1/2 0.5 除法运算为整数,使用双斜杠 >>>1//2 0 >>>5.0//2.4 ...
- Python基础教程思维导图笔记
说明:直接查看图片可能不太清楚,用浏览器打开后,按住 Ctrl ,网上滚动鼠标放大浏览器页面,可以看清楚图片
随机推荐
- Call to undefined function imageftbbox()
mac自带的php的验证码出现问题,搜索了一下Call to undefined function imageftbbox(),然后根据这个网站https://php-osx.liip.ch/本剧本机 ...
- Windows下编译protobuf v3.3.0
一:概述 关于 protobuf 在此不再多说,此处记录下成功编译步骤以备日后查阅.注意:本文并不是使用cmake gui进行编译的,如果熟悉cmake gui的话,也可以使用gui进行生成编译. 二 ...
- GitHub 给已存在的仓库增加开原协议LICENSE
如果你创建仓库时没有设置开原协议LICENSE,后续可以按下面方法增加开原协议LICENSE. 1.点击Create new file,如下图 2.文件名填LICENSE.md,右边就会出现choos ...
- centos yum命令报错
Loaded plugins: fastestmirror, security Loading mirror speeds from cached hostfile Could not retriev ...
- Linq:Group By用法
1.简单形式: var q =from p in db.Products group p by p.CategoryID into g select g; 语句描述:使用Group By按Catego ...
- delphi 查看编译版本
对照表: http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Compiler_Versions procedure TForm1.Button1Cli ...
- longest-repeating-character-replacement(难)
用sliding window的方法,之前还有个k不同元素好像也是类似的思路.有时间可以去复习下. https://leetcode.com/problems/longest-repeating-ch ...
- Maven Web项目配置Mybatis
一.添加Mybatis和数据库相关的包 1 pom.xml中添加的包有mybatis,mybatis-spring,druid,MySQL-connector-Java,commons-io,refl ...
- 如何使用 awk 的 ‘next’ 命令
导读 在 awk 系列文章中,我们来看一下next 命令 ,它告诉 awk 跳过你所提供的所有剩下的模式和表达式,直接处理下一个输入行.next 命令帮助你阻止运行命令执行过程中多余的步骤. 要明白它 ...
- centos7安装后的防火墙问题
centos7 默认使用firewall作为防火墙 停止并关闭开机自启动: systemctl stop firewalld.service #停止firewall systemctl disable ...