如何使用 Python 将 .dat 文件中包含的文件提取到文件夹位置?
我尝试使用解压缩功能:
import zipfile
import os
for file in os.listdir('directory'):
if file.endswith(".dat"):
file = 'directory' + file
with zipfile.ZipFile(file,'r') as zip_ref:
zip_ref.extractall(file)
但是这是不允许的,因为 .dat 文件不是 .zip 文件。
我设法从 .dat 中提取 .tar 文件,然后使用以下函数提取 .tar 文件:
def extract_files_from_dat(dat_file_path, output_directory):
# Open the .dat file for reading in binary mode
with open(dat_file_path, 'rb') as dat_file:
# Read the contents of the .dat file
dat_contents = dat_file.read()
# Assuming the .tar file is embedded within the .dat file,
# you'll need to extract it first before extracting its contents
# Here, we'll assume the .tar file starts at the beginning of the .dat file
# You may need to adjust this if the .tar file is located elsewhere within the .dat file
# Create a BytesIO object to simulate a file-like object from the bytes of the .dat file
from io import BytesIO
dat_bytesio = BytesIO(dat_contents)
# Open the BytesIO object as a tarfile
with tarfile.open(fileobj=dat_bytesio, mode='r') as tar:
# Extract the contents of the tar file to the output directory
tar.extractall(output_directory)