免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1730 | 回复: 0
打印 上一主题 下一主题

《python 从入门到精通》 §11 文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-26 10:18 |只看该作者 |倒序浏览


  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



st1\:*{behavior:url(#ieooui) }
/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}
§11  文件

  Normal
  0
  
  7.8 磅
  0
  2
  
  false
  false
  false
  
   
   
   
   
   
   
   
   
   
   
   
   
  
  MicrosoftInternetExplorer4



st1\:*{behavior:url(#ieooui) }
/* Style Definitions */
table.MsoNormalTable
        {mso-style-name:普通表格;
        mso-tstyle-rowband-size:0;
        mso-tstyle-colband-size:0;
        mso-style-noshow:yes;
        mso-style-parent:"";
        mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
        mso-para-margin:0cm;
        mso-para-margin-bottom:.0001pt;
        mso-pagination:widow-orphan;
        font-size:10.0pt;
        font-family:"Times New Roman";
        mso-fareast-font-family:"Times New Roman";
        mso-ansi-language:#0400;
        mso-fareast-language:#0400;
        mso-bidi-language:#0400;}
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则使用缓冲,直至使用flush或close才会存入磁盘。大数值表示缓冲大小,       –1 或者其他负数表示默认值。
              
§11.2 基本的文件方法
3种标准流:sys.stdin,sys.stdout,sys.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下面难以运行。

随机访问:
       随机访问:使用seek和tell。
      
       语法: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'
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2037260.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP