'''
@@ utf-8编码格式下,默认一个中文三个字节,一个英文活符号占用一个字节
'''
'''
1、查找目录下的文件,并将文件添加到列表对象中
'''
path = 'D:\'
for root, dirs, files in os.walk(path): # 固定遍历路径下的所有目录及文件
for i in files:
print(i) #各个文件file
if now_datetime + '.log' == i:
print("查找log成功")
t = path + "\\" + i
dir_list.append(t) #将遍历文件添加至列表
break
else:
print("查找失败")
'''
2、查找某一文件中的信息
按行查找字符串
'''
dir_list = []
for i in dir_list:
with open(i, 'r+', encoding='utf-8') as filein:
Lines = filein.readlines() #生成行对象
for line in Lines:
if line.find("查找信息") != -1:
return True
else:
return False
#len函数
str = "runoob"
print( len(str) ) # 字符串长度
l = [1,2,3,4,5]
print( len(l) ) # 列表元素个数
# ### 文件操作》》》》》》》》》》》》》》》》
'''
open 函数
fp = open("文件路径及文件名", mode = "文件处理方式", encoding = "编码规则")
fp 为open函数的生产对象
'''
# 一、文件的写入
# 1、打开文件
fp = open ("ceshi.txt", mode="w", encoding = "utf-8")
# 2、写入内容write()
fp.write("写入文件的内容")
#3、关闭文件
fp.close()
# 二、文件读取read()
fp = open("ceshi.txt",mode="r",encoding = "utf-8")
fp.read()
fp.close()
# 三、字节流的转换
'''
bytes类型:用来传输或者存储的数据格式
# encode() 编码 将字符串(包括中文)转化为字节流
# decode() 解码 将Bytes流转化为字符串
'''
#对二进制字节流的操作方法,不能指定encoding编码集
open(ceshi.txt, mode= "rb")
a = b"1234" # ->以b开头的字节流,范围只能是ASCII编码集
strvar = "我爱你"
res = strvar.encode("utf-8") #encode方法默认也是utf-8
print(res, type(res))
# 四、
#1、读取图片中的内容
fp = open("集合.png",mode = "rb")
res = fp.read()
fp.close()
#2、将读取的文件的内容存储到另一个文件中
fp = open("集合2.png",mode = "wb") #集合2.png会自动新建
fp.write(res)
fp.close()
# ##文件扩展模式
'''
read() 读取字符
seek() 调整指针位置,按字节数移动,(中文三个字节,英文数字一个字符)
tell() 当前光标左侧所有的字节数
同一文件操作时(一次open函数)注意读和写都会移动文件指针位置,导致后者读写被影响
此时1、seek()移动指针位置
2、close()后,另外重开文件再操作
'''
# 1、r+模式:先写后读
# 文件的指针默认放在文件开头位置,
fp = open("文件.txt",mode = "r+",encoding = "utf-8")
fp.write("abc")
fp.seek(0)
res = fp.read()
# 2、w+模式:可读可写
fp = open("文件.txt",mode = "r+",encoding = "utf-8")
fp.write("abc")
fp.seek(0) # 移动光标指针位置至0字节位置
res = fp.read()
fp.close()
# ## with 语法的操作 (close操作,在with语法下自动执行)
# with语法是代码块,需加上冒号 (:)
'''
#当文件不存在时会自动创建任意类型文件!!!!!!!
'''
with open ("文件.txt",mode = "r+",encoding = "utf-8") as fp:
fp.write("123")