Python 文件和内建函数 open(),file()
如何打开文件
handle = open(file_name,access_mode = 'r')
r 以读方式打开(文件不存在则报错,未提供access_mode默认值)
w 以写方式打开(文件存在则清空,不存在则创建)
a 以追加模式打开(必要时创建新文件)
r+ 以读写模式打开(参见r)
w+ 以读写模式打开(参见w)
a+ 以读写模式打开(参见a)
>>> f = open('/etc/hosts') >>> data = f.read() >>> data '127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n' >>> f.close() >>> f = open('/etc/hosts') >>> data = f.readline() >>> data '127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n' >>> data '127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n' >>> f.readlines() ['::1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n'] >>> f.readlines() [] >>> f.close()
>>> f = open('/etc/passwd') >>> f.read(10) 'root:x:0:0' >>> f.readline() ':root:/root:/bin/bash\n' >>> f.readlines() ['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', 'uucp:x:10:14:uucp:/var/spool/uucp: ..... ..... ..
文件迭代
如果需要逐行处理文件,可以结合for循环迭代文件,迭代文件的方法与处理其他序列类型的数据类似
>>> f = open('/etc/passwd') >>> for line in f: ... print line ... root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin
write方法
write()内建方法功能与read()和readline()相反,它把含有文本数据或二进制数据块的字符串写入到文件中去
写入文件时,不会自动添加行结束标志,需要程序员手工输入,添加行结束标志
>>> f = open('hi.txt','w') >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: File not open for reading >>> f.write(30) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected a string or other character buffer object >>> f.write('hello world') [root@localhost ~]# cat hi.txt [root@localhost ~]# >>> f.flush() [root@localhost ~]# cat hi.txt hello world[root@localhost ~]# >>> f.write('\n') >>> f.flush() [root@localhost ~]# cat hi.txt hello world
追加a的方式打开
>>> f = open('hi.txt','a') >>> f.write('new line\n') >>> f.close <built-in method close of file object at 0x7f551f33f540> >>> f.close() [root@localhost ~]# cat hi.txt hello world new line