python学习笔记(文件)

打开文件

open函数使用一个文件名作为唯一的强制参数,返回一个文件对象

语法:

file object = open(file_name [, access_mode][, buffering])

各个参数的细节如下:

file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。

access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。

buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

open函数使用一个文件名作为唯一的强制参数,然后返回一个文件对象。假设我要打开我硬盘(F:\python\myDemo\game.txt) 文件,可以用下面方法:

>>> f=open(r'F:\python\myDemo\game.txt')

文件模式

open 函数除了必须提供的文件名参数外,其实还有一个 mode 的模式参数,如果没有指定参数值的话,它的默认值是: rmode参数的可选值如下:

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

缓冲

open 函数的第三个参数( buffering ),表示文件的缓冲,当缓冲区大于0时(等于0时无缓冲,所有的读写操作都直接针对硬盘),Python会将文件内容存放到缓冲区(内存中),从而是程序运行的的更快,这时,只有使用 flush 或者 close 时才会将缓冲区中的数据更新到硬盘中。

基本文件方法

读和写

Write()方法

Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

Write()方法不在字符串的结尾不添加换行符('\n'):

>>> f=open('somefile.txt','wb')
>>> f.write('Python is a great language.\nYeah its great!!\n')
>>> f.close()
>>> 

read()方法

read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

>>> f=open('somefile.txt','r+')
>>> str=f.read(10)
>>> print 'Read String is : ',str
Read String is :  Python is 
>>> f.close()
>>> 

Close()方法

File对象的close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。

当一个文件对象的引用被重新指定给另一个文件时,Python会关闭之前的文件。用close()方法关闭文件是一个很好的习惯。

>>> f=open('foo.txt','wb')
>>> print 'Name of the file: ',f.name
Name of the file:  foo.txt
>>> f.close()

文件位置:

Tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后:

seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

>>> f=open('somefile.txt','r+')   #打开文件
>>> str=f.read(10)
>>> print 'Read String is :',str
Read String is : Python is 
>>> position=f.tell()     #查找文件位置
>>> print 'Current file position : ',position
Current file position :  8
>>> position=f.seek(0,0);  #把指针再次定位到文件开头
>>> str=f.read(10)
>>> print 'Again read String is : ',str
Again read String is :  Python is 
>>> f.close()  #关闭文件
>>> 

使用基本文件方法

假如somefilet.txt文件包含如下内容:

-----------------------------

Welcome to this file

There is nothing here except

This stupid haiku

-----------------------------

>>> f=open(r'f:\python\myDemo\somefile.txt')
>>> f.read(7)
'Welcome'
>>> f.close()
>>> f=open(r'f:\python\myDemo\somefile.txt')
>>> f.read()
'Welcome to this file\n\nThere is nothing here except\n\nThis stupid haiku'

>>> f.close()
>>> f=open(r'f:\python\myDemo\somefile.txt')
>>> for i in range(3):
    print str(i) +':' +f.readline()

    
0:Welcome to this file

1:

2:There is nothing here except

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

  >>> f=open('f:\python\myDemo\somefile.txt','w')
  >>> f.write('this\nis no\nhaiku')
  >>> f.close()
  >>> f=open(r'f:\python\myDemo\somefile.txt')
  >>> lines=f.readlines()
  >>> f.close()
  >>> lines[1]
  'is no\n'
  >>> lines[1]='isn\'t a\n'
  >>> f=open(r'f:\python\myDemo\somefile.txt','w')
  >>> f.writelines(lines)
  >>> f.close()
  >>>

  -----

  this

  isn't a

  haiku

 

对文件内容进行迭代 

按字节处理

最常见的对文件内容进行迭代的方法是while循环中使用read方法。例如,对每个字符进行循环,可以用下面方法实现:

f=open(filename)
char=f.read(1)
while char:
    process(char)
    char =f.read(1)
f.close()

  read方法返回的字符串会包含一个字符,直到文件末尾,read返回一个空的字符串,char将变为假。

 
  

  可以看到,char = f.read(1) 被重复地使用,代码重复通过被认为是一件坏事,看看下面的方法:

#不同的方式写循环
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()

读取所有内容

如果文件不是很大,那么可以使用不带参数的read方法一次读取整个文件,或者使用readlines方法。

f=open(filename)
for char in f.read():
    process(char)
f.close()

#用readlines迭代行
f=open(filename)
for line in f.readlines():
    process(line)
f.close()

按需加载并迭代

对文件内容进行按需加载,而不是一次性的将其从读到内存的中好处之一就是可以按需加载,节省系统资源,特别是对一些超大的文件来说更是如此。如果对大文件进行迭代操作可以考虑下面的两种方式:

用fileinput 来进行迭代

需要对一个非常大的文件进行迭代时,使用 readlines 会占用过多的内存,这时候除了可以用 while 循环和 readline 来替代,还可以通过使用for 循环和 fileinput 模块来实现懒惰迭代——即按需迭代:

import fileinput
for line in fileinput.input(filename):
    process(line)

使用文件迭代器

f=open(r'f:\python\myDemo\somefile.txt')
for line in f:
    print line
f.close()    

 可以对文件迭代器执行和普通迭代器相同的操作(list(open('filename'))和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'
>>> 

 

转载于:https://www.cnblogs.com/whats/p/4739831.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值