《Python基础教程(第二版)》学习笔记 -> 第十一章 文件和素材

时间:2023-03-08 19:49:22
《Python基础教程(第二版)》学习笔记 -> 第十一章 文件和素材

打开文件


  open函数用来打开文件,语句如下:

  open(name[,mode[,buffering]])

  open函数使用一个文件名作为唯一的强制参数,然后后返回一个文件对象。模式(mode)和缓冲(buffering)参数都是可选的。

  1. 文件模式
    open函数中模式参数的常用值
    描述
    'r'           读模式
    'w'                       写模式
    'a' 追加模式
    'b' 二进制模式(可添加到其他模式中使用)
    '+' 读/写模式(可以添加到其他模式中使用)

基本文件方法


  1. 读和写
    文件最重要的能力是提供或者接受数据。如果有一个名为f的类文件对象,那么就可以用f.write方法和f.read方法写入和读取数据。
    >>> f = open(r'c:\py\hello.txt')
    >>> f = open('c:\py\hello.txt','w')
    >>> f.write('hello,')
    >>> f.write('python!')
    >>> f.close()

    读取文件,只要告诉读多少字符(字节)即可:

    >>> f = open('c:/py/hello.txt','r')
    >>> f.read(4)
    'hell'
    >>> f.read()
    'o,python!'
  2. 使用基本文件方法
    >>> f = open(r'c:/py/hello.txt')
    >>> for i in range(4):
        print str(i)+':'+f.readline()
    
    0:hello,python!
    
    1:java
    
    2:c#
    
    3:c++

对文件内容进行迭代


对文件内容迭代:

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