python如何实现对我们操作系统及文件的管理,本文将详细的介绍给大家。
对文件的操作
打开文件的三步:打开 --> 操作 --> 关闭
一. 打开文件
f = open(’/tmp/passwdd’,‘w’)
二. 操作文件
读操作
content = f.read()
print(content)
print(f.writable())
print(f.readable())
写操作
f.write(‘hello’)
三. 关闭
f.close() #该步不可省略
文件读写
r:(默认)
-只能读,不能写
-读取的文件不存在,会报错
r+:
-可以执行读写操作
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入w:
-write only
-会清空文件之前的内容
-文件不存在,不会报错,会创建新的文件并写入w+:
-rw
-会清空文件内容
-文件不存在,不报错,会创建新的文件a:
-write only
-不会清空文件内容
-文件不存在,会报错a+:
-rw
-不清空文件内容,在末尾追加
-文件不存在,不报错
f = open('/tmp/passwd','r+')
#查看当前指针所在的位置
print(f.tell())
f.write('python')
print(f.tell())
content = f.read()
print(content)
f.close()
文件读取操作
f = open('/tmp/passwd','rb+')
print(f.read())
print(f.readline())
print(f.readlines())
#readlines():读取文件内容,返回一个列表,列表的元素分别为文件行内容
==我们的shell中有查看文件前几行的命令:head -c 4 /etc/passwd==
print(f.read(4)) #读取文件前4个字符
print(f.readline(),end='')
print(f.readlines(),end='')
print([line.strip() for line in f.readlines()])
f.close()
注意:
默认情况下读取文件的所有内容,小文件可以直接用read读取,如果
是大文件(文件大小>内存大小),不能通过read一次性读取所有内容
文件的写入操作
f.write('hello')
f.writelines(['a','b']) #将列表里的每个元素写入文件
print(f.tell())
print(f.read(3)) #从指针位置起读取3个字符
print(f.tell())
#移动文件指针
f.seek(-1,2)
print(f.read())
print(f.tell())
f.close()
seek方法,移动指针
seek的第一个参数是偏移量:>0,表示向右移动,<0表示向左移动
seek的第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾
非纯文本文件读取
读取文本文件:
r r+ w w+ a a+
读取二进制文件:
rb rb+ wb wb+ ab ab+
"""
f1 = open('hello.png',mode='rb')
content = f1.read()
f1.close()
f2 = open('111.jpg',mode='wb')
f2.write(content)
f2.close()
京东面试题
"""
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
01-AF-3B
01-AF-3B-xx
01-AF-3B-xx-xx
01-AF-3B-xx-xx-xx
"""
import string
import random
def create_mac():
mac = '01-AF-3B'
for i in range(3):
n = random.sample(string.hexdigits,2)
sn = '-' + ''.join(n).upper()
mac += sn
return mac
with open('mac.txt','w+') as f:
for i in range(100):
mac = create_mac()
print(mac)
f.write(mac+'\n')
上下文管理器
with open('/tmp/passwd') as f:
#使用这种文件的打开方式更加简单了,同时可以避免忘记关闭文件的情况
print(f.read())
同时打开两个文件
with open('/tmp/passwd') as f1,\
open('/tmp/passwd1','w+') as f2:
#将第一个文件的内容写入第二个文件中
f2.write(f1.read())
#移动指针到文件最开始
f2.seek(0)
#读取文件内容
print(f2.read())
练习
"""
创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数
"""
import random
f = open('data.txt','w+')
for i in range(100000):
f.write(str(random.randint(1,100)) + '\n')
f.seek(0)
print(f.read())
f.close()