Python中可以使用:
file(name, [mode, [buffering]] ) -> file object 和 open(name, [ mode, [ buffering ]])来打开文件。
【说明】name是文件的名称,若文件不存在,将会首先创建名称为name的文件,然后打开;mode是文件的打开模式;buffering设置缓存模式,buffering=0表示不缓存,buffering=1表示行缓存,如果buffering大于1,则表示缓存区的大小,单位为字节。
使用file()函数或者open()函数,可以打开文件,并获得一个file object对象,file object常用的属性和方法:
file的常用属性和方法
($)使用write()进行文件内容的写入:
content = """Hello World
Python studying"""
f = file("hello.txt", "w")
f.write(content)
f.close()
查看文件目录,可以看到文件系统中出现了hello.txt的文件:
查看hello.txt文件的内容,如下:
【说明】可以使用opne()函数代替file()函数。
(1)文件的读取
Python中文件的读取主要使用read(), readline()和readlines()函数完成。
(1-1)readline()按行读取
readline()函数每次读取文件中的一行,下面是从文件hello.txt文件中读取每一行,并打印:
# coding=utf-8
f = open("hello.txt", 'r')
while True:
line = f.readline()
if line:
print line, # ,号表示不需换行
else:
break
f.close()
打印结果:
Hello World
Python studying
Process finished with exit code 0
(1-2)readlines()多行读取
readlines()函数可以将文件中的内容按行读取出来,放入列表中,并将列表返回:
# coding=utf-8
f = open("hello.txt", 'r')
lines = f.readlines()
for line in lines:
print line,
print type(lines)
打印结果:
Hello World
Python studying
<type 'list'>
Process finished with exit code 0
(1-3)read()函数一次性读取
read([size])函数一次性将文件内容读取出来,size为读取文件的大小,若size省略,表示全部读取:
# coding=utf-8
f = open("hello.txt", "r")
content = f.read(5) # 读取文件中前5个字节的内容
print content
print f.tell() # 打印文件指针当前的位置
f.seek(0) # 将文件指针移动到文件的开头
content = f.read() # 读取文件所有的内容
print content
f.close()
打印结果:
Hello
5
Hello World
Python studying
Process finished with exit code 0
(2)文件的写入
Python中可以使用write()函数,writelines()函数实现文件内容的写入。
(2-1)write()写入内容到文件中:
# coding=utf-8
f = open("hello.txt", 'a+')
content = "hust"
f.write(content)
f.close()
f = open("hello.txt", "r")
content = f.read()
print content
f.close()
打印结果:
Hello World
Python studying
hust
Process finished with exit code 0
(2-2)writelines()函数可以将列表中的内容,依次写入到文件中去:
# coding=utf-8
f = open("hello.txt", "w")
list = ["Hello\t", "World\n", "Hello", "Hust"]
f.writelines(list)
f.close()
f = open("hello.txt", "r")
content = f.read()
print content
打印结果:
Hello WorldH
elloHust
Process finished with exit code 0