python对文件进行读写操作
python进行文件读写的函数是open或filefile_handler = open(filename,,mode)
Table mode
模式
描述
r
以读方式打开文件,可读取文件信息。
w
以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容
a
以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建
r+
以读写方式打开文件,可对文件进行读和写操作。
w+
消除文件内容,然后以读写方式打开文件。
a+
以读写方式打开文件,并把文件指针移到文件尾。
b
以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。
Table 文件对象方法
方法
描述
f.close()
关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。
f.fileno()
获得文件描述符,是一个数字
f.flush()
刷新输出缓存
f.isatty()
如果文件是一个交互终端,则返回True,否则返回False。
f.read()
读出文件,如果有count,则读出count个字节。
f.readline()
读出一行信息。
f.readlines()
读出所有行,也就是读出整个文件的信息。
f.seek(offset[,where])
把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。
f.tell()
获得文件指针位置。
f.truncate()
截取文件,使文件的大小为size。
f.write(string)
把string字符串写入文件。
f.writelines(list)
把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。
例子如下:
读文件
Python代码
[*]read = open(result)
[*] line=read.readline()
[*] while line:
[*] print line
[*] line=read.readline()#如果没有这行会造成死循环
[*] read.close
写文件
Python代码
[*]read = file(result,'a+')
[*] read.write("\r\n")
[*] read.write("thank you")
[*] read.close
其它
Python代码
[*]#-*- 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 'seek(15) function' #移位到第15个字符,从16个字符开始显示余下内容
[*]filehandler.seek(15)
[*]print 'tell() function'
[*]print filehandler.tell() #显示当前位置
[*]print filehandler.read()
[*]
[*]filehandler.close() #关闭文件句柄
1 #!/usr/bin/env python
2 """create text file """
3
4 import os
5
6
7 def write(self,user_input):
8 fname = user_input;
9 ls = os.linesep
10 all = []
11 print "\nEnter lines('.' by itself to quit).\n"
12 while True:
13 entry = raw_input('>')
14 if entry == '.':
15 break
16 else:
17 all.append(entry)
18 fobj = open(fname, 'w')
19 fobj.writelines(["%s%s"%(x,ls) for x in all])
20 fobj.flush();
21 fobj.close()
22 print 'DONE!'
23
24 def read(self, user_input):
25 fname = user_input;
26 if os.path.exists(fname):
27 fobj = open(fname, 'r')
28 for echoline in fobj
29 print echoline
30 fobj.close();
页:
[1]