python对文件进行读写操作

python进行文件读写的函数是open或file

file_handler = open(filename,,mode)

Table mode

模式

描述

r

以读方式打开文件,可读取文件信息。

w

以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容

a

以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建

r+

以读写方式打开文件,可对文件进行读和写操作。

w+

消除文件内容,然后以读写方式打开文件。

a+

以读写方式打开文件,并把文件指针移到文件尾。

b

以二进制模式打开文件,而不是以文本模式。该模式只对WindowsDos有效,类Unix的文件是用二进制模式进行操作的。

 

Table 文件对象方法

方法

描述

f.close()

关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。

f.fileno()

获得文件描述符,是一个数字

f.flush()

刷新输出缓存

f.isatty()

如果文件是一个交互终端,则返回True,否则返回False

f.read([count])

读出文件,如果有count,则读出count个字节。

f.readline()

读出一行信息。

f.readlines()

读出所有行,也就是读出整个文件的信息。

f.seek(offset[,where])

把文件指针移动到相对于whereoffset位置。where0表示文件开始处,这是默认值 1表示当前位置;2表示文件结尾。

f.tell()

获得文件指针位置。

f.truncate([size])

截取文件,使文件的大小为size

f.write(string)

string字符串写入文件。

f.writelines(list)

list中的字符串一行一行地写入文件,是连续写入文件,没有换行。


例子如下:

读文件

 read = open(result)
        line=read.readline()
        while line:
              print line
              line=read.readline()#如果没有这行会造成死循环
        read.close

 写文件

read = file(result,'a+')
        read.write("\r\n")
        read.write("thank you")
        read.close

 其它

#-*- encoding:UTF-8 -*-
filehandler = open('c:\\111.txt','r')    #以读方式打开文件,rb为二进制方式(如图片或可执行文件等)

print 'read() function:'              #读取整个文件
print filehandler.read()

print 'readline() function:'          #返回文件头,读取一行
filehandler.seek(0)
print filehandler.readline()

print 'readlines() function:'         #返回文件头,返回所有行的列表
filehandler.seek(0)
print filehandler.readlines()

print 'list all lines'                #返回文件头,显示所有行
filehandler.seek(0)
textlist = filehandler.readlines()
for line in textlist:
    print line,
print 
print

print 'seek(15) function'               #移位到第15个字符,从16个字符开始显示余下内容
filehandler.seek(15)
print 'tell() function'
print filehandler.tell()              #显示当前位置
print filehandler.read()

filehandler.close()                   #关闭文件句柄
 
发布了94 篇原创文章 · 获赞 2 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章