Python内置函数open()详解&文件属性方法详解

Python文件对象打开模式及其属性方法详解

1、文件系统和文件

文件系统:文件系统是OS用于明确磁盘或分区上的文件的方法和数据结构,即在磁盘上组织文件的方法

文件:存储在某种长期储存设备或临时存储设备中的一段数据流,并且受计算机文件系统管理。

概括来讲,文件是计算机中有OS管理的具有名字的存储区域,在Linux系统上,文件名被看做是字节序列

文件<---010100010101010101101-->进程  

2、Python打开文件

Python内置函数open()用于打开文件或创建文件对象

open(file_name[mode,[bufsize]])

         file_name:文件名

var_name =open(file_name[mode,[bufsize]])

         mode:指定文件的打开模式

                   r:只读open('/var/log/access.log','r')                   

                   w:写入

                   a:附加

         在模式后使用“+”表示同时支持输入、输出操作,如:

                   r+:读写模式,默认以读模式打开,不会自动创建文件

                   w+:写读模式,默认以写模式打开,会自动创建文件

                   a+:附加模式

         在模式后附加“b”表示以二进制方式打开文件,如:rb、wb、ab、rb+、wb+、ab+

                   bufsize:输出缓冲

                   0: 禁用

                   负数:使用系统默认缓冲

                   1:使用缓冲,只缓冲一行数据

                   2+:指定缓冲空间大小

3、文件对象属性和方法

f1.close():关闭文件

f1.flush():清除输出缓冲区      

f1.next():返回下一行或引发stopTteration,在Python3中,对应方法为f.__next__()

f1.seek(offset[whence]):查找新文件位置,whence:起点,0: 从文件头,1:从当前位置,2:从文件尾部

file.seek(offset[whence])

         whence:起点

                   0:从文件头

                   1:从当前位置

                   2:从文件尾部

         offset:偏移量

f1.writelines(line):写入序列line中的所有字符串

f1.read(n):最多读取n个字节

f1.softspace:布尔值,指示在使用print语句时,是否应该在一个值之前打印空格字符。

f1.xreadlines:读取文件,向下兼容

f1.encoding:文件编码。如果没有使用任何编码该值为none

f1.closed:布尔值,表示状态,已打开则False,已关闭则为True

f1.mode:文件的   I/O模式

f1.readinto()   

f1.tell():返回当前文件指针       

f1.errors

f1.name:如果使用open()创建文件,则为文件名称,否则,它将是一个表示文件来源的字符串       

f1.readline([n]):读取单行输入的最多n个字符,如果省略n,则读取整行

f1.truncate([n]):将文件截断为最多n个字符    

f1.fileno():返回一个整数文件描述符,从3开始

f1.newlines:在通用换行符模式下打开一个文件,该属性包含可在文件中实际找到的换行符吧表示。

         如果没有找到换行符,该值为none,将会看到一个包含'\n','\r'或'\r\n'的字符串,或者一个包含所有不同换行符的元组

f1.readlines([size]):读取所有行并返回一个列表,size用于指定在读取操作停止前在文件上读取的近似字符数  

f1.write(s):写入字符串  

f1.isatty():是否是终端设备文件

4、Python文件操作示例

例1:只读模式打开/etc/passwd               

In [1]: f1 = open('/etc/passwd','r')    #只读模式打开

In [2]: type(f1)

Out[2]: file     #文件类型:file

In [3]: f1.      #使用.访问内置方法  

f1.close       f1.flush       f1.next        f1.seek        f1.writelines

f1.closed      f1.isatty      f1.read        f1.softspace   f1.xreadlines

f1.encoding    f1.mode        f1.readinto    f1.tell       

f1.errors      f1.name        f1.readline    f1.truncate   

f1.fileno      f1.newlines    f1.readlines   f1.write      

In [3]: f1.next()    #使用成员函数next()返回迭代器下一个元素

Out[3]: 'root:x:0:0:root:/root:/bin/bash\n'

In [4]: f1.next()

Out[4]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [5]: f1.close()     #close()关闭文件    

In [6]: f1.next()     #文件关闭时迭代器元素指向无法使用

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

ValueError                                Traceback (mostrecent call last)

<ipython-input-6-4a9d57471e88> in<module>()

----> 1 f1.next()

ValueError: I/O operation on closed file

In [7]: f1 = open('/etc/passwd','r')

#返回文件描述符,0标准输入,1,标注输出,2,标准错误输出

In [8]: f1.fileno()       #使用fileno()查看文件描述符   

Out[8]: 3

In [9]: f1.fileno()

Out[9]: 3

In [10]: f1.readline()  #使用readline()成员函数读一行文件,注意文件位置会偏移到下一行  

Out[10]:'root:x:0:0:root:/root:/bin/bash\n'

In [11]: f1.readline()   

Out[11]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [12]: f1.readlines()   #使用readlines()函数读取所有行并返回一个列表

Out[12]:

['daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',

 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',

 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',

...,

 'redis:x:495:492:Redis DatabaseServer:/var/lib/redis:/sbin/nologin\n']

In [13]: f1.readline()

Out[13]: ''

In [14]: f1.tell()     #tell()函数返回当前文件指针

Out[14]: 1966

In [15]: f1.seek(0)   #seek(0)重新指定文件开始查找位置,从头部开始。

In [16]: f1.tell()

Out[16]: 0

In [17]: f1.readline()

Out[17]:'root:x:0:0:root:/root:/bin/bash\n'

In [18]: f1.seek(0)

In [19]: f1.read(10)

Out[19]: 'root:x:0:0'

In [20]: f1.tell()

Out[20]: 10

In [21]: f1.next()

Out[21]: ':root:/root:/bin/bash\n'

In [22]: f1.next()

Out[22]: 'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [23]: f1.name     #返回文件名

Out[23]: '/etc/passwd'

例2:读写模式打开/tmp/passwd

In [1]: f1 = open('/tmp/passwd','r+')

In [2]: f1.next()

Out[2]: 'root:x:0:0:root:/root:/bin/bash\n'

In [3]: f1.tell()

Out[3]: 1966

In [4]: f1.seek(0,2)

In [5]: f1.tell()

Out[5]: 1966

In [6]: f1.write('new line,test.\n')   #使用write()函数在文件末尾添加一行

In [7]: f1.tell()

Out[7]: 1981

In [8]: f1.close()

In [9]: exit

[root@test ~]# tail -n 2 /tmp/passwd

redis:x:495:492:Redis DatabaseServer:/var/lib/redis:/sbin/nologin

new line,test.

#末尾添加成功

例3:写读模式打开一个新文件/tmp/test.unl,并写入内容

In [1]: f2 = open('/tmp/test.unl','w+')

In [2]: f2.write('hello,world!\nhow areyou\n')

In [3]: f2.close()

[root@test ~]# cat /tmp/test.unl

hello,world!

how are you

例4:各种模式下文件打开方式异同

In [1]: f2 = open('/tmp/test.unl','w+')

In [2]: f2.write('hello,world!\nhow areyou\n')

In [3]: f2.close()

#写读模式下,默认以写模式打开文件,文件不存在会新建

In [4]: f3 = open('/tmp/1test.txt','r')

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

IOError                                   Traceback(most recent call last)

<ipython-input-1-8ead05602c24> in<module>()

----> 1 f3 = open('/tmp/1test.txt','r')

IOError: [Errno 2] No such file ordirectory: '/tmp/1test.txt'

#读模式下,打开一个不存在的文件会引发IOError

In [5]: f3 = open('/tmp/tmp1.txt','r+')

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

IOError                                   Traceback(most recent call last)

<ipython-input-1-542f9a700881> in<module>()

----> 1 f3 = open('/tmp/tmp1.txt','r+')

IOError: [Errno 2] No such file ordirectory: '/tmp/tmp1.txt'

#读写模式下,打开一个不存在的文件同样会引发IOError,因为读写模式默认以读模式打开,所以文件必须存在。

In [6]: f3 = open('/tmp/tmp.txt','a')

In [7]: f1.isatty()   #是否是tty终端文件

Out[7]: False

In [8]: f3.close()

In [9]: exit

In [1]: f3 = open('/tmp/tmp.unl','a')

#附加模式下打开一个不存在的文件并写入内容,均不会报错,所以该模式下打开一个不存在的文件会新建。

In [3]: f3.write('hello,world!\nhow areyou\n')

In [4]: f3.flush()

In [5]: f3.readline()

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

IOError                                   Traceback(most recent call last)

<ipython-input-5-abe2a9ccc8b5> in<module>()

----> 1 f3.readline()

IOError: File not open for reading

#读文件内容时触发IOError,所以附加模式下,文件并未打开,写入时只是把内容追加到结尾处。

In [6]: f4 = open('/tmp/tmp2.unl','a+')

In [7]: f4.write('hello,world!\nhow areyou\n')

In [8]: f4.flush()

In [9]: f4.readline()

Out[9]: ''

In [11]: f4.tell()

Out[11]: 25

In [12]: f4.seek(0)

In [13]: f4.readline()

Out[13]: 'hello,world!\n'

In [14]: f4.readline()

Out[14]: 'how are you\n'

#附加读写模式下,写入文件并刷新内存读写文件写入内容,不会引发IOError,所以附加模式下,文件打开。

例5:文件成员函数在for循环中的应用

In [1]: s1 = 'abc'

In [2]: s2 = 'xy'

In [3]: s1 + s2

Out[3]: 'abcxy'

In [4]: s1.join(s2)

Out[4]: 'xabcy'

In [5]: s2 = 'xyzk'

In [6]: s1.join(s2)

Out[6]: 'xabcyabczabck'

In [7]: s1 + '\n' 

Out[7]: 'abc\n'

In [8]: f1 = open('/tmp/test0526.txt','w+')

In [9]: for line in ( i**2 for i inrange(1,11) if i%2 == 0):

  ....:    f1.write(str(line)+'number_test\n')

  ....:    

In [10]: f1.flush()

[root@test tmp]# cat test0526.txt

4number_test

16number_test

36number_test

64number_test

100number_test

例6、常见成员方法

In [1]: f1 = open('/tmp/passwd','w+')

In [2]: f1.isatty()    #文件是否是终端tty文件

Out[2]: False

In [3]: f1.encoding  #文件编码。如果没有使用任何编码该值为none

In [4]: f1.softspace

Out[4]: 0

In [5]: f1.closed    #文件是否打开

Out[5]: False

In [6]: f1.close() 

In [7]: f1.closed 

Out[7]: True


  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值