考前复习:
path 有4个:path.exists path.isdir path.isfile path.join
dir 有3个:mkdir rmdir listdir
还有一个remove用于删除文件
路径用 \\
打开:with open(‘文件名’,’r w a rb wb’,encoding=’utf-8 gbk’) as file
读取:readlines readline read(size)
写入:write writelines(list)
移动游标:
seek(位置下标)
seek(delta,2) seek(delta,1) 分别表示末尾和当前位置,用rb
创建文件:
import os
name=r'empty_directory'
print(os.getcwd())
if(os.path.exists(name)):
print('please quit')
else:
os.mkdir(name)
读取文件:
file=open('lzp.txt','r')
content=file.read()
print(content)
print(file.read())
file.seek(0)
print(file.read())
file.seek(0)
lines=file.readlines()
print(len(lines))
file.seek(0)
count=0
for line in file:
print(count,line)
print(type(count),type(line))
file.close()
给图片加密:
import os
file_path=r"docs/image.jpg"
para=10
if os.path.exists(file_path):
print("File exists!")
with open(file_path,'rb') as file:
content=bytearray(file.read())
print(type(content))
original_content=content[:para]
content[:para]=b'\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'
with open(file_path,'wb') as file:
file.write(content)
with open(r'docs/key.dat','wb') as file:
file.write(original_content)
else:
print("File not exists!")
给图片解密:
import os
file_path=r"docs/image.jpg"
para=10
if os.path.exists(file_path):
print("File exists!")
with open(file_path,'rb') as file:
content=bytearray(file.read())
with open(r'docs/key.dat','rb') as file:
original_content=bytearray(file.read())
with open(file_path,'wb') as file:
content[:para]=original_content
file.write(content)
else:
print("File not exists!")
在文件中间写:
import os
with open('lzp.txt','r+') as file:
file.seek(3)
file.write('gg')
with open('lzp.txt','r') as file:
print(file.read())