# 通过文件头判断文件格式
# 如果有后缀直接识别为后缀,主要针对无后缀文件
# 实现识别文件
import os
def get_file_type(file_path):
with open(file_path, 'rb') as f:
file_head = f.read(4)
if file_head[:3] == b'\xff\xd8\xff':
return 'JPEG'
elif file_head[:4] == b'\x89PNG':
return 'PNG'
elif file_head[:3] == b'ID3':
return 'MP3'
elif file_head[:4] == b'%PDF':
return 'PDF'
else:
return 'unknown'
if __name__ =="__main__":
file_path = '/test/'
names = os.listdir(file_path)
for name in names:
path = file_path + name
houzhui = os.path.splitext(path)[-1].lower()
if houzhui:
print(houzhui)
else:
file_type = get_file_type(path)
print(file_type)
# os.rename(path, path+'.'+file_type)
# 通过文件头判断文件格式
# 如果有后缀直接识别为后缀,主要针对无后缀文件
# 实现识别文件