Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19729703
  • 博文数量: 679
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 9308
  • 用 户 组: 普通用户
  • 注册时间: 2006-07-18 10:51
文章分类

全部博文(679)

文章存档

2012年(5)

2011年(38)

2010年(86)

2009年(145)

2008年(170)

2007年(165)

2006年(89)

分类: Python/Ruby

2009-08-26 10:18:44

文件


2009-8-26

磁针石:xurongzhong#gmail.com

博客:oychw.cublog.cn

§11.1 打开文件             

       语法:open(name[, mode[, buffering]])            

f = open(r'C:\somefile.txt'),如果文件不存在则会报错。默认是只有只读权限的。

 

 

'r' Read mode

'w' Write mode

'a' Append mode

'b' Binary mode (added to other mode)

'+' Read/write mode (added to other mode)

 

python中的文件和unix中一样,行尾使用“\n"windows中使用”\r\n“。文本模式下python会进行自动转换。二进制需要保留原数据,不需要任何转换,所以有'b'参数。使用’U‘则是使用统一字符模式。

      

buffer如果为0,则不使用缓冲;如果为1则使用缓冲,直至使用flushclose才会存入磁盘。大数值表示缓冲大小,       –1 或者其他负数表示默认值。

             

§11.2 基本的文件方法

3种标准流:sys.stdinsys.stdoutsys.stderr。它们都是文件或者类似文件的对象。

 

>>> f = open('c:\somefile.txt', 'w')

>>> f.write('Hello, ')

>>> f.write('World!')

>>> f.close()

 

写入的结果:Hello, World!

 

读取实例:

 

>>> f = open('c:\somefile.txt', 'r')

>>> f.read(4)

'Hell'

>>> f.read()

'o, World!'

 

实例11-1:统计单词数:

#!/usr/bin/env python

# somescript.py

import sys

text = sys.stdin.read()

words = text.split()

wordcount = len(words)

print 'Wordcount:', wordcount

 

该实例在windows下面难以运行。

 

随机访问:

       随机访问:使用seektell

      

       语法:seek(offset[, whence])

       whence默认为0,表示从左到右,也可以为1,可前可后,为2则是从右到左。

      

       >>> f = open(r'c:\text\somefile.txt', 'w')

>>> f.write('01234567890123456789')

>>> f.seek(5)

>>> f.write('Hello, World!')

>>> f.close()

>>> f = open(r'c:\text\somefile.txt')

>>> f.read()

'01234Hello, World!89'

 

 

       ftell指明当前的位置:

      

 

>>> f = open(r'c:\text\somefile.txt')

>>> f.read(3)

'012'

>>> f.read(2)

'34'

>>> f.tell()

5L

 

读写行:

              someFile.readline()读取一行,返回'Hello, World!\n'someFile.readline(5)返回'Hello'readlines返回为列表。writelines则相反。因为有write,所以没有writeline方法。换行符是需要自己添加的。

             

关闭文件:

       # Open your file here

try:

# Write data to your file

finally:

file.close()

       也可以使用如下方法:

       with open("somefile.txt") as somefile:

do_something(somefile)

       with实际上是context manager,它支持__enter____exit__方法。__enter__没有参数,返回值为as后面的变量,__exit__3个参数:an exception type, an exception object, and an exception traceback

       基本的文件方法:

       f.read()读取所有

      

       >>> import pprint

>>> pprint.pprint(open(r'c:\text\somefile.txt').readlines())

['Welcome to this file\n',

'There is nothing here except\n',

'This stupid haiku']

 

 

 

§11.3 重复操作文件

f = open(filename)

char = f.read(1)

while char:

process(char)

char = f.read(1)

f.close()

 

另外一种方法:

f = open(filename)

while True:

char = f.read(1)

if not char: break

process(char)

f.close()

 

读取行:

f = open(filename)

while True:

line = f.readline()

if not line: break

process(line)

f.close()

 

列表的形式:

f = open(filename)

for char in f.read():

process(char)

f.close()

 

f = open(filename)

for line in f.readlines():

process(line)

f.close()

 

读取部分文件:

import fileinput

for line in fileinput.input(filename):

process(line)

 

老的版本使用xreadlines,现在被input代替了。

 

文件的迭代器:

 

f = open(filename)

for line in f:

process(line)

f.close()

 

由于python会自动关闭文件,甚至可以更简单:

for line in open(filename):

process(line)

 

import sys

for line in sys.stdin:

process(line)

 

>>> 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'

阅读(4710) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~