#1.open内置函数打开文件,返回值是一个文件对象;默认文件打开方式——只读#新建一个文件hello[kiosk@fundation86 Desktop]$ touch hello#open内置函数打开文件f = open("/home/kiosk/Desktop/hello")# 如果文件不存在, open() 函数就会抛出一个 IOError 的错误,并且给出错误码和详细的信息告诉你文件不存在print type(f)#<type 'file'>#2.读取文件内容f.read()#如果文件打开成功,接下来,调用 read() 方法可以一次读取文件的全部内容#3.关闭文件f.close()#文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源。
with open("/etc/passwd") as f2: print f2.read()
>>> f = open('/root/test.jpg', 'rb')>>> f.read()
import codecswith codecs.open('/Users/michael/gbk.txt', 'r', 'gbk') as f:f.read()
from collections import Iterablef = open("/etc/passwd")print isinstance(f, Iterable)# 文件对象可以 for 循环遍历;for i in f: print if.close()# for i in f.readlines:#print i
# 返回 bool 值,判断文件对象的状态;print f.closed# 查看文件的打开模式print f.mode# 查看文件名print f.name
f = open("/home/kiosk/Desktop/hello",'w')f.write("westos")f.close()
f = open("/home/kiosk/Desktop/hello",'a+')f.write("hello")f.seek(0.0)print f.tell()f.read()
f = open("/etc/passwd", 'r')# 程序员常用操作:print [i.strip() for i in f.readlines()][:5]f.close()
f = open("/home/kiosk/Desktop/hello",'a+')print f.read()f.writelines(["hello\n", "python\n", "java\n"])# 程序员常用操作:# help(f.writelines)f.seek(0)f.close()
with open("/home/kiosk/Desktop/hello") as f: for line in f: if line.strip()[0] != "#": print line ,
with open("/etc/passwd") as f1: # 遍历文件的每一行内容 ; for line in f1: # 字符串的替换 bline = line.replace("root", "westos") with open("/home/kiosk/Desktop/tmp/passwd", "a+") as f2: # 写入新文件 f2.write(bline)
联系客服