“”"
打开文件的三步:打开 --> 操作 --> 关闭
“”"
#打开文件
f = open('/tmp/passwd','r+')
#读操作
content = f.read()
print(content)
print(f.writable())
print(f.readable())
#写操作
f.write('hello')
read = f.read()
print(read)
#关闭
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():读取文件内容,返回一个列表,列表的元素分别为文件
行内容
"""
head -c 4 /etc/passwd
print(f.read(4))
print(f.readline(),end='')
print(f.readlines(),end='')
#
f.close()
print([line.strip() for line in f.readlines()])
默认情况下读取文件的所有内容,小文件可以直接用read读取,如果
是大文件(文件大小>内存大小),不能通过read一次性读取所有内容
#文件的写入操作
f.write('hello')
f.writelines(['a','b']) #将列表里的每个元素写入文件
print(f.tell())
print(f.read(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()
f = open('/tmp/passwd')
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()
5.系统
#1.返回操作系统类型
#值为:posix,表示linux操作系统,如果是nt,是windows操作系统
print(os.name)
#2.操作系统的详细信息
info = os.uname()
print(info)
print(info.sysname)
print(info.nodename)
#3.系统环境变量
print(os.environ)
#4.通过key值获取环境变量对应的value值
print(os.environ.get('PATH'))
#
#1.判断是否为绝对路径
print(os.path.isabs('/tmp/westos'))
print(os.path.isabs('data.txt'))
#2.生成绝对路径
print(os.path.abspath('hello.png'))
print(os.path.join('/home/kiosk','hello.png'))
print(os.path.join(os.path.abspath('.'),'hello.jpg'))
#3.获取目录名或文件名
filename = '/home/kiosk/PycharmProjects/20190316/day07/hello.png'
print(os.path.basename(filename))
print(os.path.dirname(filename))
#4.创建目录/删除目录
os.mkdir('img')
os.makedirs('img/jpg/png')
os.rmdir('img')
#5.创建文件/删除文件
os.mknod('aa.txt')
os.remove('aa.txt')
#6.文件重命名
os.rename('data1.txt','data.txt')
#7.判断文件或者目录是否存在
print(os.path.exists('data1.txt'))
#8.分离后缀名和文件名
print(os.path.splitext('hello.png'))
#9.将目录名和文件名分离
print(os.path.split('/tmp/hello/python.jpg'))
练习:
1.在当前目录新建目录img, 里面包含100个文件, 100个文件名
各不相同(X4G5.png)
2. 将当前img目录所有以.png结尾的后缀名改为.jpg.
“”"
def gen_code(len=4):
#随机生成4位验证码
li = random.sample(string.ascii_letters + string.digits,len)
#将列表元素拼接为字符串
return ''.join(li)
def create_files():
#随机生成100个验证码
li = [gen_code() for i in range(100)]
os.mkdir('img')
for name in li:
os.mknod('img/' + name + '.png')
create_files()
def modify_suffix(dirname,old_suffix,new_suffix):
"""
:param dirname: 要操作的目录
:param old_suffix: 之前的后缀名
:param new_suffix: 新的后缀名
:return:
"""
if os.path.exists(dirname):
#找出所有以old_suffix结尾的文件名
pngfile = filter(lambda filename:filename.endswith(old_suffix),os.listdir(dirname))
#将文件名和后缀分开
basefiles = [os.path.splitext(filename)[0] for filename in pngfile]
#文件重命名
for filename in basefiles:
oldname = os.path.join(dirname,filename+old_suffix)
newname = os.path.join(dirname,filename+new_suffix)
os.rename(oldname,newname)
print('%s重命名为%s成功' %(oldname,newname))
else:
print('%s不存在,无法操作...' %dirname)
modify_suffix('dir','.jpg','.png')
练习
- 生成一个大文件ips.txt,要求1200行,
每行随机为172.25.254.0/24段的ip; - 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
import random
def create_ipfile(filename):
ip = ['172.25.254.'+str(i) for i in range(0,255)]##生成ip
with open(filename,'a+') as f:
for count in range(1200):
f.write(random.sample(ip,1)[0]+'\n') ##随机选择生成的ip,1200次
def sort_by_ip(filename,count=10):
ips_dict = dict() ##定义空字典用来存放ip,及其次数
with open(filename) as f:
for ip in f: ##将ip及其出现次数放入字典
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
##按照value值降序排序,然后取前十位
return sorted_ip
create_ipfile('ips.txt')
print(sort_by_ip('ips.txt'))
生成100个MAC地址并写入文件中,MAC地址前6位(16进制)为01-AF-3B
01-AF-3B-xx-xx-xx
import string
import random
def create_MAC():
MAC = '01-AF-3B'
num = string.hexdigits ##生成十六进制数
for i in range(3): ##三对
n = random.sample(num,2) ##随机选两个16进制数
sn = '-' +''.join(n).upper()##大写转化,并用'-'连接
MAC += sn ##与开头拼接
return MAC
def main():
with open('mac.txt','w') as f: ##写入方式打开文件
for i in range(100): ##共生成100个
mac = create_MAC()
print(mac)
f.write(mac+'\n') ##写入文件
main()