一、文件基本操作
1.打开文件的三步
1.打开
2.操作
3.关闭(如果不关闭会占用文件描述符)
2.打开文件
f = open('/tmp/passwdd','w')
3.操作
1).读操作
f.read()
content = f.read()
print(content)
2).写操作
f.write('hello')
4.关闭
f.close()
二、文件读写
r:(默认)
-只能读,不能写
-读取的文件不存在,会报错
f = open('/tmp/passwdd')
r+:
-可以执行读写操作
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入w:
-write only
-会清空文件之前的内容
-文件不存在,不会报错,会创建新的文件并写入w+:
-rw
-会清空文件内容
-文件不存在,不报错,会创建新的文件a:
write only
不会清空文件之前的内容
文件不存在,会报错,写在后面
a+:
可读可写
不会清空文件之前的内容
文件不存在不会报错,会建立文件,再写入
1.文件是否可读可写
f = open('/tmp/passwdd')
print(f.writable())
print(f.readable())
3.查看当前指针所在的位置
print(f.tell())
2.文件的读取操作
readlines():读取文件内容,返回一个列表,列表的元素分别为文件行内容
.strip() 去空格(广义)
f = open('/tmp/passwd','rb+') #b--二进制文件
print(f.read()) #读取字节个数
print(f.readline()) #读取一行
print(f.readlines()) #读取多行
print(f.read(4))
print(f.readline(),end='')
默认情况下读取文件的所有内容,小文件可以直接用read读取,如果
是大文件(文件大小>内存大小),不能通过read一次性读取所有内容
3.文件的写入操作
f=open('test.txt','a+')
f.write('hello\n')
f.writelines(['a','b']) #将列表里的每个元素写入文件
f.seek(0) #指针移动到文件开头
print(f.read())
f.close()
4.移动文件指针
seek方法,移动指针
seek的第一个参数是偏移量:>0,表示向右移动,<0表示向左移动
seek的第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾
f = open('test.txt','rb+')
print(f.tell()) #读之前的指针位置
print(f.read(3))
print(f.tell()) #读之后的指针位置
f.seek(-1,2) #移动指针位置
print(f.tell())
f.close()
5.非纯文本文件读取
读取文本文件:
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()
三、上下文管理器
不用写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()
四、系统
import os #导入系统模块
from os.path import exists,splitext,join
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('data.txt','data1.txt')
7.判断文件或者目录是否存在
print(os.path.exists('data1.txt'))
8.分离后缀名和文件名
print(os.path.splitext('hello.png'))
9.将目录名和文件名分离
实例:
"""
# # 练习:
# # 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')
"""
# 京东二面笔试题
# 1. 生成一个大文件ips.txt,要求1200行,
每行随机为172.25.254.0/24段的ip;
# 2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip;
"""
import random
def create_ip_file(filename):
ip =['172.25.254.' + str(i) for i in range(0,255)]
print(random.sample(ip,1))
# print(ip)
with open(filename,'a+') as f:
for count in range(1200):
f.write(random.sample(ip,1)[0] + '\n')
# create_ip_file('ips.txt')
def sorted_by_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f:
for ip in f:
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]
return sorted_ip
print(sorted_by_ip('ips.txt'))
"""
生成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 random
import string
num = string.hexdigits
def create_mac():
MAC = '01-AF-3B'
hex_num = string.hexdigits
for i in range(3):
n = random.sample(hex_num,2) #select from hex_num
sn = '-' + ''.join(n).upper()
MAC += sn
return MAC
def Mac():
with open('mac.txt','w+') as f:
for i in range(100):
a = create_mac()
f.write(a + '\n')
Mac()