Home  >  Article  >  Backend Development  >  Python 文件和输入输出小结

Python 文件和输入输出小结

WBOY
WBOYOriginal
2016-06-06 11:27:441077browse

1.打开和关闭文件(open(),file(),close())

有两种内建函数可以获取文件对象:open和file。他们的用法完全一样。下面只以open()为例子讲解。获取一个文件对象(打开文件)的语法如下:       

代码如下:

fileObj = open(filename,access_mode='r',buffering=-1) 

filename不用说你也应该知道是你要打开文件的路径。
access_mode用来标识文件打开的模式,默认为r(只读)。

常用的模式如下表所示:

文件模式 解释
r 以只读方式打开
w 以写方式打开,文件不为空时清空文件;文件不存在时新建文件。
a 追加模式,没有则创建
r+,w+,a+ 以读写模式打开,参见w,a

另外还有一个b表示二进制模式访问,但是对于Linux或者unix系统来说这个模式没有任何意义,因为他们把所有文件都看作二进制文件,包括文本文件。


第三个参数不经常用到,标识访问文件的缓冲方式,0代表不缓冲,1代表缓
冲一行,-1代表使用系统默认缓冲方式。只要使用系统默认就好。

一些例子:

代码如下:


>>> f = open('/etc/passwd','r')
>>> f1 = open('/etc/test','w')

使用完文件后,一定要记得关闭文件,操作如下:

代码如下:


>>> f.close()

2.文件读入

2.1.file.read(size = -1)
    读取从当前文件游标起size个字节的文件内容。如果size=-1,则读取所有剩余字节。

代码如下:


>>> f = open('/etc/passwd')
>>> f.read(100)
'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nol'

2.2.file.readlines(size=-1)

    从文件中读取并返回一行(包括行结束符),或返回最大size个字符

代码如下:


>>> f.readline()
'ogin\n'#和上面一个例子输出的最后拼起来就是  'nologin',因为游标在l后面。
>>> f.readline(1)
'a'

2.3.file.readlines(sizhint=0)
    读取文件所有的行,并作为一个列表返回(包括行结束符),如果sizhint>0则返回总和大约sizhint字节的行(具体由缓冲区大小决定)。

代码如下:


f.readlines()
['dm: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', ......

输出省略。

3.文件输出

3.1.file.write(str)
    向文件中写入指定的字符串。

代码如下:


>>> f = file('/root/test.py','w+')
>>> f.write("print 'hello,world'")
>>> f.read()
''
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'"

3.2.file.write(seq)

    向文件写入字符串序列seq。seq是任何返回字符串的可迭代对象。

代码如下:


>>> f = file('/root/test.py','a+')
>>> codelst = ['\n','import os\n',"os.popen('ls').read()\n"]
>>> f.writelines(codelst)
>>> f.close()
>>> file('/root/test.py','r').read()
"print 'hello,world'\nimport os\nos.popen('ls').read()\n"

注意,文件写入的时候,不会自动加上换行符,必须手动加上。

4.文件移动

    学过C语言的同学,一定对fseek()函数不陌生,在Python中,seek()方法是fseek()的替代者。

    seek(offset,whence=0)
    方法可以将文件游标移动到文件的任意位置。其中offset代表需要移动的偏移字节数,whence表示要从哪个位置开始偏移:
    0代表从文件开头开始算起,
    1代表从当前位置开始算起,
    2代表从文件末尾算起。

    那我们如何知道当前文件游标在哪里呢?别担心,这里有个tell()方法可以返回当前文件游标的位置。

5.文件迭代

    在Python中,文件不仅仅是一个对象,而且是一个可迭代对象!我们可以利用如下迭代方式,轻松的访问和处理文件内容,而不必全部读出(readlines)后再迭代(性能上差了很多哦!)

代码如下:


for eachline in f:
    #dealwith eachline of f

例如:

代码如下:


>>> for eachline in f:
...     print eachline

6.os、os.path与文件

os和os.path中提供了一些跟文件有关的接口,下面介绍一些常用的接口。其他接口可以自己查阅相关文档。

注意:以下函数传入的参数都是字符串形式的文件名字,文件名可由文件对象的name属性获得。

函数 描述
os.path.basename() 去掉目录路径,返回文件名
os.path.dirname() 去掉文件名,返回目录路径
os.path.getatime()
os.path.getctime()
os.path.getmtime()
os.path.size()
返回文件的atime,ctime,mtime和大小
os.path.exists() 该文件或目录是否存在
os.path.abs() 指定路径是否为绝对路径
os.path.isdir() 路径是否存在且为目录
os.path.isfile() 路径是否存在且为文件。
os.path.islink() 指定路径是否存在且为一个符号链接

代码如下:


>>> import os.path
>>> f = open('/root/test.py','r')
>>> os.path.basename(f.name)
'test.py'
>>> f.name
'/root/test.py'
>>> os.path.getsize(f.name)
52
>>> os.path.isabs(f.name)
True
>>> os.path.isdir(f.name)
False

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn