Я создаю код Python для распаковки ZIP-файла и вывода содержимого в другой.
Зип-файл содержит множество файлов, имена некоторых из которых чувствительны к регистру, например
T_N_with_ client.docx
T_N_with_
lient.docx.
Я использовал ExtractAll, чтобы извлечь все в ZIP-файл, однако после бег кода, в выходной папке есть только один файл, указанный ниже
T_N_with_client.docx Однако содержимое файла на самом деле является содержимым T_N_with_Client.docx.
Что вызывает эту ошибку и как я могу убедиться, что программа учитывает файлы с одинаковыми именами, но с разными заглавными буквами?< /p>
Большое спасибо.
import os
import zipfile
from pathlib import Path
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def list_zip_contents(zip_file_path):
"""Lists all files in a zip file without extracting."""
try:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
contents = zip_ref.namelist()
print(f"ZIP file contains {len(contents)} files:")
for file in contents:
print(f"{file}")
return contents
except (zipfile.BadZipFile, OSError) as e:
print(f"Error reading the zip file: {e}")
raise
def extract_zip(zip_file_path, extraction_dir):
"""Extracts a zip file to the specified directory without altering any files."""
try:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(extraction_dir)
print(f"All files have been extracted to: {extraction_dir}")
except (zipfile.BadZipFile, OSError) as e:
print(f"Error extracting the zip file: {e}")
raise
def main():
try:
# Open GUI to select the input zip file
Tk().withdraw() # Hide the root window
zip_file_path = askopenfilename(title="Select the zip file", filetypes=[("Zip files", "*.zip")])
if not zip_file_path:
print("No file selected. Exiting.")
return
if not os.path.isfile(zip_file_path):
print("Invalid file path. Please check and try again.")
return
# List contents of the ZIP file
try:
zip_contents = list_zip_contents(zip_file_path)
except Exception as e:
print("Failed to list contents of the zip file. Exiting.")
return
# Extract to a directory with the same name as the source zip file (without extension)
extraction_dir = os.path.splitext(zip_file_path)[0]
try:
os.makedirs(extraction_dir, exist_ok=True)
except OSError as e:
print(f"Error creating extraction directory: {e}")
return
# Extract the ZIP file
try:
extract_zip(zip_file_path, extraction_dir)
except Exception as e:
print("Failed to extract zip file. Exiting.")
return
# Count files in the extracted directory
extracted_files = list(Path(extraction_dir).rglob("*"))
print(f"Extracted directory contains {len(extracted_files)} files:")
for file in extracted_files:
print(f" {file}")
except OSError as e:
print(f"An OS error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Подробнее здесь: https://stackoverflow.com/questions/793 ... -sensitive
ZIP-файл Python ExtractAll не чувствителен к регистру ⇐ Python
Программы на Python
1737654421
Гость
Я создаю код Python для распаковки ZIP-файла и вывода содержимого в другой.
Зип-файл содержит множество файлов, имена некоторых из которых чувствительны к регистру, например
T_N_with_[b] c[/b]lient.docx
T_N_with_
lient.docx.
Я использовал ExtractAll, чтобы извлечь все в ZIP-файл, однако после бег кода, в выходной папке есть только один файл, указанный ниже
T_N_with_[b]c[/b]lient.docx Однако содержимое файла на самом деле является содержимым T_N_with_Client.docx.
Что вызывает эту ошибку и как я могу убедиться, что программа учитывает файлы с одинаковыми именами, но с разными заглавными буквами?< /p>
Большое спасибо.
import os
import zipfile
from pathlib import Path
from tkinter import Tk
from tkinter.filedialog import askopenfilename
def list_zip_contents(zip_file_path):
"""Lists all files in a zip file without extracting."""
try:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
contents = zip_ref.namelist()
print(f"ZIP file contains {len(contents)} files:")
for file in contents:
print(f"{file}")
return contents
except (zipfile.BadZipFile, OSError) as e:
print(f"Error reading the zip file: {e}")
raise
def extract_zip(zip_file_path, extraction_dir):
"""Extracts a zip file to the specified directory without altering any files."""
try:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(extraction_dir)
print(f"All files have been extracted to: {extraction_dir}")
except (zipfile.BadZipFile, OSError) as e:
print(f"Error extracting the zip file: {e}")
raise
def main():
try:
# Open GUI to select the input zip file
Tk().withdraw() # Hide the root window
zip_file_path = askopenfilename(title="Select the zip file", filetypes=[("Zip files", "*.zip")])
if not zip_file_path:
print("No file selected. Exiting.")
return
if not os.path.isfile(zip_file_path):
print("Invalid file path. Please check and try again.")
return
# List contents of the ZIP file
try:
zip_contents = list_zip_contents(zip_file_path)
except Exception as e:
print("Failed to list contents of the zip file. Exiting.")
return
# Extract to a directory with the same name as the source zip file (without extension)
extraction_dir = os.path.splitext(zip_file_path)[0]
try:
os.makedirs(extraction_dir, exist_ok=True)
except OSError as e:
print(f"Error creating extraction directory: {e}")
return
# Extract the ZIP file
try:
extract_zip(zip_file_path, extraction_dir)
except Exception as e:
print("Failed to extract zip file. Exiting.")
return
# Count files in the extracted directory
extracted_files = list(Path(extraction_dir).rglob("*"))
print(f"Extracted directory contains {len(extracted_files)} files:")
for file in extracted_files:
print(f" {file}")
except OSError as e:
print(f"An OS error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
Подробнее здесь: [url]https://stackoverflow.com/questions/79382088/python-zipfile-extractall-is-not-being-case-sensitive[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия