文件处理

*文件是计算机中由 OS 管理的具有名字的存储区域
*在 linux 系统上,文件是被看作字节序
*文件能被存储的前提是,一定能够做到序列化

1.open (三种模式)

* python 的内置函数 open 用于打开文件或者创建文件对象
    open(name[,mode[,bufsize]]) 
    open 方法可以接收三个参数: 文件名 | 模式  | 缓冲区参数
    & open 函数返回的是一个文件对象
    & mode 指定打开文件模式 
        *默认只读
        r:只读 | w:只写 | a:追加 
        r+:读入   | w+:写入 | a+:
        b——以二进制模式打开文件
        rb | wb | ab | rb+ | wb+ | ab+

    & bufsize 定义输出缓存
        0——表示无缓存输出
        1——表示使用缓冲   #通常只缓存一行数据
        负数——表示使用系统默认位置
        正数——表示使用近似指定文件大小的缓存

*方法只有通过文件对象才能调用,不应该通过类型调用
In [1]: file.
file.close       file.isatty      file.read        file.tell
file.closed      file.mode        file.readinto    file.truncate
file.encoding    file.mro         file.readline    file.write
file.errors      file.name        file.readlines   file.writelines
file.fileno      file.newlines    file.seek        file.xreadlines
file.flush       file.next        file.softspace   

In [1]: f1 = open('/etc/passwd','r')    # 注:'' 引号必须有

In [2]: type(f1)
Out[2]: file

In [3]: f1.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.next()
Out[5]: 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'

In [6]: f1.close()  #注意:有 open 就有 close

In [7]: f1.next()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4a9d57471e88> in <module>()
----> 1 f1.next()

ValueError: I/O operation on closed file

2.file.fileno() 文件描述符

*内核(kernel)利用文件描述符(file descriptor)来访问文件
*文件描述符在形式上是一个非负整数。实际上,它是一个索引值,指向内核为每一个进程所维护的该进程打开文件的记录表。当程序打开一个现有文件或者创建一个新文件时,内核向进程返回一个文件描述符。在程序设计中,一些涉及底层的程序编写往往会围绕着文件描述符展开。但是文件描述符这一概念往往只适用于UNIX、Linux这样的操作系统。

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

In [9]: f1.fileno()     #返回的一般都是很小的整数,一般从3开始计数
Out[9]: 5

3.file.readline() | file.readlines()

取一行出来   | 以列表形式返回每一行宝库奥行结束符,每一行都是一个元素

In [10]: f1.readl
f1.readline   f1.readlines  

In [10]: f1.readline()      #返回一行
Out[10]: 'root:x:0:0:root:/root:/bin/bash\n'

In [11]: f1.readlines()     #返回所有行,包括行结束符
Out[11]: 
['bin:x:1:1:bin:/bin:/sbin/nologin\n',
 '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',
 'sync:x:5:0:sync:/sbin:/bin/sync\n',
 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n',
 'halt:x:7:0:halt:/sbin:/sbin/halt\n',
 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n',
 'operator:x:11:0:operator:/root:/sbin/nologin\n',
 'games:x:12:100:games:/usr/games:/sbin/nologin\n',
 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n',
 'nobody:x:99:99:Nobody:/:/sbin/nologin\n',
 'avahi-autoipd:x:170:170:Avahi IPv4LL Stack:/var/lib/avahi-autoipd:/sbin/nologin\n',
 'systemd-bus-proxy:x:999:997:systemd Bus Proxy:/:/sbin/nologin\n',
 'systemd-network:x:998:996:systemd Network Management:/:/sbin/nologin\n',
 'dbus:x:81:81:System message bus:/:/sbin/nologin\n',
 'polkitd:x:997:995:User for polkitd:/:/sbin/nologin\n',
 'tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin\n',
 'unbound:x:996:993:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n',
 'colord:x:995:992:User for colord:/var/lib/colord:/sbin/nologin\n',
 'usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n',
 'geoclue:x:994:991:User for geoclue:/var/lib/geoclue:/sbin/nologin\n',
 'saslauth:x:993:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n',
 'libstoragemgmt:x:992:990:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin\n',
 'abrt:x:173:173::/etc/abrt:/sbin/nologin\n',
 'setroubleshoot:x:991:989::/var/lib/setroubleshoot:/sbin/nologin\n',
 'rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n',
 'rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n',
 'chrony:x:990:988::/var/lib/chrony:/sbin/nologin\n',
 'radvd:x:75:75:radvd user:/:/sbin/nologin\n',
 'qemu:x:107:107:qemu user:/:/sbin/nologin\n',
 'rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n',
 'nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin\n',
 'pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin\n',
 'gdm:x:42:42::/var/lib/gdm:/sbin/nologin\n',
 'gnome-initial-setup:x:989:984::/run/gnome-initial-setup/:/sbin/nologin\n',
 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n',
 'postfix:x:89:89::/var/spool/postfix:/sbin/nologin\n',
 'ntp:x:38:38::/etc/ntp:/sbin/nologin\n',
 'sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin\n',
 'tcpdump:x:72:72::/:/sbin/nologin\n',
 'kiosk:x:1000:1000:kiosk:/home/kiosk:/bin/bash\n',
 'apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n',
 'student:x:1001:1001::/home/student:/bin/bash\n']

In [12]: f1.readline()      #到文件尾部 | 文件是通过类似于游标(指针)的方式读取的
Out[12]: ''

In [13]: f1.readline()
Out[13]: ''

4.file.tell() | 查看指针位置

In [14]: 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 [14]: f1.tell()      #返回的是位置的字节数
Out[14]: 2368


4.file.seek() | 指定指针偏移量
        seek(offset[,whence])
            offset:偏移量
            whence:从什么位置开始偏移
                0——从文件头部开始偏移
                1——从当前位置向后偏移
                2——从文件尾部开始偏移


In [14]: f1.tell()      #原位置
Out[14]: 2368

In [15]: f1.seek(15,2)  #从尾部开始偏移

In [16]: f1.tell()
Out[16]: 2383

In [17]: f1.seek(15,0)  #从头部开始偏移

In [18]: f1.tell()
Out[18]: 15

In [19]: f1.seek(0)     #回到文件头 | 默认从文件头部开始偏移

In [20]: f1.tell()
Out[20]: 0


*偏移到第二行
next
file.read() | 明确指出读多少个字节
    read([size])

In [24]: f1.seek(0)

In [25]: f1.read(10)
Out[25]: 'root:x:0:0'

5.file.name | 调用当前文件名称,是一种属性不是方法

In [26]: f1.name    
Out[26]: '/etc/passwd'

In [27]: f1.name()      #不需要括号,因为是一种属性,不是方法
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-bd689fe2ed10> in <module>()
----> 1 f1.name()

TypeError: 'str' object is not callable

In [28]: 

6.file.write()

*写入时要确保打开文件时,给了 w 权限
*file.flush() | 刷新

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.seek(0,2)    #从文件末尾开始,偏移 0 个字节

In [4]: f1.tell()
Out[4]: 2368

In [5]: f1.write('new line.\n')     如果需要换行,需要自己加上换行符

In [6]: f1.tell()   #此时文件里面还看不出来新添加的
Out[6]: 2378

In [7]: f1.flush()  #刷新 | 执行此动作之后,就可以查看到文件里面新添加的内容

7.权限

*关于读

r:只读   #默认是只读权限
r+:读写
#打开不存在的文件时会报错

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
In [4]: f=open("meiyou.txt","r")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-4-071df569c745> in <module>()
----> 1 f=open("meiyou.txt","r")

IOError: [Errno 2] No such file or directory: 'meiyou.txt'
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

*关于写

w:只写
w+:读写
***注意:打开时文件已被清空
#打开不存在的文件时会自动创建
#写入时之前的内容会被覆盖掉(>)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
In [1]: fo = open("hello.txt","w")

In [2]: fo.write("So good !")

In [3]: fo.write("So good !")

In [4]: fo.clos
fo.close   fo.closed  

In [4]: fo.close()


#要close之后才能查看到内容
[root@foundation30 python]# cat hello.txt 
So good !So good !



In [9]: fo=open("/mnt/python/hello.txt","w+")

In [10]: fo.read()
Out[10]: ''

In [11]: fo.clo
fo.close   fo.closed  

In [11]: fo.close()


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

关于a

a:只写
a+:可读可写

#文件不存在时自动创佳
#写入时内容是追加的(>>)


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
In [5]: fo = open("hello.txt","a")

In [6]: fo.writ
fo.write       fo.writelines  

In [6]: fo.write("I am a student")

In [7]: fo.close()


[root@foundation30 python]# cat hello.txt 
So good !So good !I am a student
#如果需要换行,则加\n就可以
In [8]: fo = open("hello.txt","a")

In [9]: fo.write("\nI am a student\n")

In [10]: fo.close()

[root@foundation30 python]# cat hello.txt 
So good !So good !I am a student
I am a student
[root@foundation30 python]# 

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

8.文件读取

readseek(偏移量,选项)    #移动指针
    偏移量: >0(向右)  <0(向左)
    选项:0(开始) 2(结尾)  1(当前)
#每读一次,都需要移动指针
readline:返回字符串
readlines:返回列表
next:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
In [2]: fo=open("hello.txt","a+")

In [3]: fo.read()
Out[3]: 'hello\n'

In [4]: fo.write("\nfentiao")

In [5]: fo.flush()

In [6]: fo.re
fo.read       fo.readinto   fo.readline   fo.readlines  

In [6]: fo.read()
Out[6]: ''

In [7]: fo.seek(0,0)

In [8]: fo.read()
Out[8]: 'hello\n\nfentiao'

In [9]: fo.seek(0,0)

In [10]: fo.next()  #next查找完之后就会报错
Out[10]: 'hello\n'

In [11]: fo.next()
Out[11]: '\n'

In [12]: fo.next()
Out[12]: 'fentiao'

In [13]: fo.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-13-11b076a55610> in <module>()
----> 1 fo.next()

StopIteration: 

In [14]: fo.seek(0,0)

In [15]: fo.readlines() #以列表形式返回
Out[15]: ['hello\n', '\n', 'fentiao']

In [16]: fo.readline()
Out[16]: ''

In [17]: fo.seek(0,0)   #移动指针

In [18]: fo.readline()
Out[18]: 'hello\n'

In [19]: l=["nihao","123"]

In [20]: fo.write(l)    #write不能用来添加列表
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-6e3b7021d346> in <module>()
----> 1 fo.write(l)

TypeError: expected a character buffer object

In [21]: fo.writelines(l)   #添加列表必须要使用writelines

In [22]: fo.flush() #使自己写入的东西立即生效,不必要在等到close之后

In [23]: fo.seek(0,0)       #移动指针

In [24]: fo.readlines()     #以列表形式返回
Out[24]: ['hello\n', '\n', 'fentiaonihao123']


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

练习1:
统计文件中某个字符串重复的次数
[root@foundation30 python]# cat repeat.py 
#!/bin/env python
#coding:utf-8
import re
fo=open("/mnt/python/hello.txt","a+")
hello_list=re.findall(r"hello",fo.read())
count=len(hello_list)
print "Search %s hello" %count
fo.close()
[root@foundation30 python]# python repeat.py 
Search 3 hello
[root@foundation30 python]# cat hello.txt 
hello
nihao
hello
so
taha
hello
[root@foundation30 python]# 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值