• python学习笔记之十:文件和素材


    这里将介绍函数和对象--文件和流,让你在程序调用期间存储数据,并且可以处理来自其他程序的数据。

    一. 打开文件

    1.1 open函数

    open函数用来打开文件,语法如下:open(name,[.mode[.buffer]])

    它有唯一一个强制参数,就是文件名,然后返回一个文件对象。参数-模式和缓冲都是可选的。

    使用范例:(如果文件不存在,就会报错)

    >>> f = open('c:\text\test.txt')   #windows下
    
    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        f = open('c:	ext	est.txt')
    IOError: [Errno 22] invalid mode ('r') or filename: 'c:	ext	est.txt'

    (1)模式

    如果要向文件中写入内容,则必须提供一个模式参数来显式声明。读取文件对象时指定或不指定读模式是一样的效果。

    下面是模式常用值:

    值                描述
    ‘r’              读模式
    'w'              写模式
    'a'              追加模式
    'b'              二进制模式(可添加到其他模式中):改变处理文件的方法,如二进制文件 ‘rb’
    '+'              读/写模式(可添加到其他模式中):‘r+’表示读写

    (2)缓冲

    open函数的第三个参数控制着文件的缓冲。

    如果参数是0,I/O就是无缓冲的,所有读写操作都是直接针对硬盘的;

    如果参数是1,I/O就是有缓冲的,用内存代替硬盘,让程序更快,只有使用flush或者close时才会更新硬盘上的数据;

    如果参数大于1,参数的数字代表缓冲区的大小;

    如果参数是-1,代表使用默认的缓冲区大小;

    二. 基本文件方法

    2.1 读和写:假设test.txt文本中存了“hello,world!”

    (1)读:f.read(字符个数),可以指定字符个数,不指定时,会读取之前读取过的全部剩余部分;

    >>> f = open('D:\python\test.txt')
    >>> f.read(3)
    'hel'
    >>> f.read()
    'lo,world!'

    注意:在读取文件时,可以省略模式说明,因为‘r’是默认的。

    (2)写:f.write(string),新写入的数据会覆盖掉原有的数据,在关闭文件前,后续的write操作内容会被追加到文件已存在部分的后面;

    >>> f = open('D:\python\test.txt','r+')
    >>> f.write(' bangbangjiang')
    >>> f.write('hao')
    >>> f.read()
    ' bangbangjianghao'
    >>> f.read()

    2.2 管道输出

    在UNIX的shell中,使用管道可以在一个命令后面续写其他的多个命令。

    例如: $ cat somefile.txt | python somesctript.py | sort

    第一个命令是把somefile.txt中的内容写到标准输出;

    第二个命令运行了一个python脚本,脚本内容应该是从标准输入读,把结果写入到标准输出;

    第三个命令是从标准输入读取所有的文本,按字母排序,然后把结果写入标准输出;

    管道符合“|”就是将一个命令的标准输出和下一个命令的标准输入连在一起。

    2.3 读写行

    (1) file.readline():读取单独的一行,从当前位置开始直到一个换行符的出现(不同平台上的换行符查看os.linesep);如果含有参数(非负的整数),它表示读取的字符最大值。

    >>> f = open('D:\python\test.txt')
    >>> for i in range(3):
        print str(i) + ':' + f.readline()
    
        
    0:hello,world!
        
    1:welcome to here!
    
    2:there is nothing!

    >>> f.close()

    注意:上面的例子可以看出,换行符也会被读出!!读出的句子之间都有一个空行。

    (2) file.readlines():读取一个文件的所有行并将其作为列表返回;

    >>> f = open('D:\python\test.txt')
    >>> f.readlines()
    ['hello,world!
    ', 'welcome to here!
    ', 'there is nothing!']

    (3) file.writelines():参数是一个字符串列表,它会把所有的字符串写入文件。注意,程序不会增加新行,需要自己添加。

    >>> f = open('D:\python\test.txt')
    >>> lines = f.readlines()
    >>> lines
    ['I 
    ', 'am 
    ', 'a writer!']
    >>> f.close()
    >>> f = open('D:\python\test.txt','w')
    >>> lines[1] = 'am not
    '
    >>> f.writelines(lines)
    >>> f.close()
    
    #文本内容如下:
    I 
    am not
    a writer!

    2.4 关闭文件

          通常一个文件对象在退出程序后会自动关闭,但是对于写入过的文件总是应该关闭,因为python可能会缓存写入的数据,如果程序因为某些原因崩溃了,那么数据根本不会被写入文件,为了安全起见,要在使用完文件后关闭。

          如果想确保文件被关闭,那么应该使用try/finally语句,并且在finally子句中调用close方法。

    f = open('D:\python\test.txt','w')
    try:
        f.write("sss")
    finally:
        f.close()

         事实上,还有一个语句专门是为这种情况设计的:with

    with open('D:\python\test.txt','w') as f:
        f.write("aaaa")

    文件在语句结束之后会被自动关闭,即便是由于异常引起的结束也是这样。

    三. 对文件内容进行迭代

    对文件内容进行迭代以及重复执行一些操作,是最常见的文件操作之一。

    假设do_something.py中有一个函数叫do_something(),运行之:

    def do_something(string):
        print "hello, " , string

    3.1 按字节处理

    最常见的对文件内容进行迭代的方法是在while循环中使用read方法。

    >>> f.open('do_something.py')
    >>> while True:
           char = f.read(1)
           if not char:break
           do_something(char)

    hello,  def do_something(string):

    hello,      print "hello, " , string

    hello, 
    >>> f.close()

    3.2 按行操作

    当处理文件时,经常对文件的行进行迭代。

    >>> f.open('do_something.py')
    >>> while True:
           line = f.readline()
           if not line:break
           do_something(line)

    hello,  def do_something(string):

    hello,      print "hello, " , string

    hello, 
    >>> f.close()

    3.3 读取所有内容

    如果文件不大,可以用read()方法一次读取整个文件,但如果文件比较大,使用readlines方法比较好。

    >>> f.open('do_something.py')
    >>> for char in f.read():
           do_something(char)

    hello,  def do_something(string):

    hello,      print "hello, " , string

    hello, 
    >>> f.close()

    或者:

    >>> f.open('do_something.py')
    >>> for line in f.readlines():
           do_something(line)

    hello,  def do_something(string):

    hello,      print "hello, " , string

    hello, 
    >>> f.close()

    3.4 使用fileinput实现懒惰行迭代

    在需要对一个非常大的文件进行行迭代时,readlines所占用的内存会非常多。用for循环可以使用一个名为懒惰行迭代的方法,说它懒惰是因为它只是读取实际需要的文件部分。

    >>> import fileinput
    >>> for line in fileinput.input('D:\python\do_something.py'):
             do_something(line)
        
    hello,  def do_something(string):
    
    hello,      print "hello, " , string
    
    hello,  

    3.5 文件迭代器

    从2.2版本的python开始,文件对象是可迭代的!这意味着可以直接在for循环中使用它们,从而对它们进行迭代。

    f = open('D:\python\do_something.py')
    >>> for line in f:
        do_something(line)
    
        
    hello,  def do_something(string):
    
    hello,      print "hello, " , string
    
    hello,  
    
    >>> f.close()

    注意:sys.stdin是可迭代的,就是其他的文件对象:

    >>> import sys
    >>> for line in sys.stdin:
        do_something(line)
  • 相关阅读:
    NFS与通配符
    yum管理RPM包与linux网络设置
    git常用命令总结——覆盖日常开发全操作
    inner join on会过滤掉两边空值的条件
    入园第一天
    P3750 [六省联考2017]分手是祝愿 题解
    CSP2021 爆零记
    CSP 前模板记录(黄题篇)
    对拍
    2021.10.20CSP模拟模拟赛 赛后总结
  • 原文地址:https://www.cnblogs.com/bangbangjiang/p/3419955.html
Copyright © 2020-2023  润新知