老男孩python学习自修

第一天    文件IO处理

1.读文件实例

file_split.python

f = file('myFile.txt', 'r')
for line in f.readlines():
        line = line.strip('\n').split(':')
        print line

myFile.txt

##
# User Database
# 
# Note that this file is consulted directly only when the system is running
# in single-user mode.  At other times this information is provided by
# Open Directory.
#
# See the opendirectoryd(8) man page for additional information about
# Open Directory.
##
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico

结果:

 
 

['##']

 
 

['# User Database']

 
 

['# ']

 
 

['# Note that this file is consulted directly only when the system is running']

 
 

['# in single-user mode.  At other times this information is provided by']

 
 

['# Open Directory.']

 
 

['#']

 
 

['# See the opendirectoryd(8) man page for additional information about']

 
 

['# Open Directory.']

 
 

['##']

 
 

['nobody', '*', '-2', '-2', 'Unprivileged User', '/var/empty', '/usr/bin/false']

 
 

['root', '*', '0', '0', 'System Administrator', '/var/root', '/bin/sh']

 
 

['daemon', '*', '1', '1', 'System Services', '/var/root', '/usr/bin/false']

 
 

['_uucp', '*', '4', '4', 'Unix to Unix Copy Protocol', '/var/spool/uucp', '/usr/sbin/uucico']

 

2.文件读写模式

r  只读

w  只写

a  追加

r+b   读写

w+b  写读

a+b  追加及读

f = file('myFile.txt', 'r')
import tab
f.readlines()
f.close()
//这段命令为读取所有行,以只读模式打开则不能写入

f = file('myFile.txt', 'w')
f.write('new line')
f.close()
//以只写模式打开文件,则无法读取文件,写的时候会覆盖

f = file('myFile.txt', 'a')
f.write('second line')
f.write('\nthird line')
f.flush()
//追加方式打开文件,从最后面写入

//文件内容的写入时机:
用户输入内容时,内容存放在缓冲区,当缓冲区的内容大于1M时自动写入文件
调用flush()或者close()方法时将内容从缓冲区写入文件

 只读模式下写入文件时报错如下:

>>> f.write('new lines')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: File not open for writing

 3.文件的编码:

写入中文实例

#!/usr/bin/env python
#_*_ coding:UTF-8 _*_

f = file('myFile.txt', 'w')
f.write(u'你是小狗'.encode('UTF-8'))
f.flush()
f.close()
//注意:写入中文需要制定编码为UTF-8;并且写入时需要指定编码

4.文件io的主要方法:

f.close()  关闭文件

f.closed()  文件是否被其他程序打开后关闭;为False则表示该文件正在被其他程序打开进行写操作

f.mode  文件的读写模式

f.read()  读取文件的所有内容以字符串的方式返回

f.readline()  读取文件的一行以字符串的方式返回

f.readlines()  读取文件的所有内容以列表的方式返回

f.next()  迭代器,f.readlines()内部是使用该方法实现的

f.seek()  跳到文件的第几个字符串前面

f.tell()  告诉我光标在文件的第几个字符的位置

猜你喜欢

转载自www.cnblogs.com/liuzhiqaingxyz/p/9302963.html