1,文件基本操作
r:-只能读 不能写
-读取文件不存在,是会报错
r+:- 可以执行读写操作,但写的内容会覆盖;
- 文件不存在, 报错;
w:-只能写,不能读
-会清空文件内容
-文件不存在,会新建文件
w+:- rw
- 文件不存在, 不报错
- 会清空文件内容
a:-只能写
-不会清空问文件内容
-文件不存在,会新建文件
a+:- rw
- 文件不存在, 不报错
- 不会清空文件内容
图一:
图二
图三:
2,文件操作的三部曲:打开,操作,关闭
eg1:
f = open('/home/kiosk/Desktop/passwd','r')
content = f.read()
print content
f.close()
eg2:
f = open('passwdss', 'a')
#print f.read()
f.write('hello')
f.close()#不关闭占用系统资源,造成卡顿
3,文件指针
文件指针
文件指针标记从哪个位置开始读取数据
第一次打开文件时,通常文件指针会指向文件的开始位置
当执行了read方法后,文件指针会移动到读取内容的末尾
思考:如果执行了一次read方法,读取了所有内容,那么再次调用read方法,还能够获取到内容么?
答:不能,第一次读取后,文件指针移动到了文件末尾,再次调用不会读取到任何内容
file = open('passwd')
text = file.read()
print text
print type(text)
print len(text)
print '**********'
# 移动文件指针到文件开头
#file.seek(0)
text = file.read()
print text
print len(text)
file.close()
图一:
图二:
4,逐行读取整个文件
file = open('passwd')
while True: #为什么要设定为无限循环:因为我们不知道循环的条件(因为我们不知道文件有多少行)
text = file.readline()
# 判断是否读取到内容
# 如果文件指针到文件的最后一行,那么就读取不到内容了
if not text:
break
# 每读取一行的末尾已经有一个'\n'
print text
file.close()
5,打开已有文件,并写到另一个文件
1)小文件
# 小文件的复制
# 源文件以只读的方式打开
file_read = open('passwd')
# 目标文件以只写的方式打开
file_write = open('passwd_copy','w')
#从源文件中读取内容
text = file_read.read()
# 将读取到的内容写到目标文件
file_write.write(text)
# 关闭文件
file_read.close()
file_write.close()
6,读取二进制文件
读取二进制文件的时候
rb rb+ wb wb+ ab ab+
# 先读取二进制文件内容,保存在变量里面
f1 = open('hello.jpg',mode='rb')
content = f1.read()
f1.close()
f2 = open('happy.png',mode='wb')
f2.write(content)
f2.close()
效果:happy.png
7,另类文件打开方式
with open('passwd') as f:
lines = f.readlines()
print lines
for line in lines:
print line'