Files
parser_csv/csv_parser.py

75 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import csv
import os
from datetime import datetime, timedelta
from glob import glob
import shutil
import webbrowser
from time import sleep, time
# папка для загрузки файлов с помощью браузере, должна быть пустой
in_dir_download_files = '/home/lobanov/Загрузки'
# список файлов csv в начальной директории
list_files = [file for file in os.listdir('csv_files') if file.endswith('.csv')]
dt_start = datetime.now().utcnow()
print(dt_start)
for file in list_files:
try:
os.mkdir(f'{file[0:-4]}') # создаем директорию для файлов
except FileExistsError:
pass
print(file[0:-4])
with open(f'csv_files/{file}', encoding='utf-8') as f:
cnt_document = 0
parse_project = list(csv.reader(f, delimiter=';'))
for idx, row in enumerate(parse_project):
if row[8] and row[8] != 'Прикрепленные файлы':
temp_address = []
sleep(1)
lst_address = row[8].split('\n')
for address in lst_address:
cnt_document += 1
file_not_exist = False
start_time = time()
webbrowser.open(address)
sleep(1)
# проверяем и если надо, ждем, начался ли скачиваться файл, скачался ли он, файлов больше 1го
while len(os.listdir(in_dir_download_files)) == 0 or glob(f'{in_dir_download_files}/*.part') or len(
os.listdir(in_dir_download_files)) > 1:
if time() - start_time > 10 and len(os.listdir(in_dir_download_files)) == 0:
print('-------------------------')
print(f'файл не найден примерная строка {idx}')
print('-------------------------')
file_not_exist = True
break
if time() - start_time > 300 and len(os.listdir(in_dir_download_files)) > 1:
print('X' * 20)
print(f'файлов несколько в директории загрузки. Проверить примерно {idx} строку')
print('X' * 20)
for file_name in os.listdir(in_dir_download_files):
os.remove(f'{in_dir_download_files}/{file_name}')
print("Deleted " + str(file_name))
file_not_exist = True
break
sleep(0.5)
if file_not_exist:
continue
try:
new_path_to_file = shutil.move(
f'{in_dir_download_files}/{os.listdir(in_dir_download_files)[0]}', f'{file[0:-4]}')
except shutil.Error:
new_path_to_file = shutil.move(
f'{in_dir_download_files}/{os.listdir(in_dir_download_files)[0]}',
f'{file[0:-4]}/{idx}_{os.listdir(in_dir_download_files)[0]}')
temp_address.append(new_path_to_file)
row[8] = '\n'.join(temp_address)
with open(f'{file[0:-4]}_local.csv', 'w') as fp:
file_writer = csv.writer(fp, delimiter=';')
file_writer.writerows(parse_project)
print(cnt_document, 'Количество ссылок')
print(len(os.listdir(file[0:-4])), 'Количество документов')
sleep(5) # перерыв между файлами csv
dt_stop = datetime.now().utcnow()
print(dt_stop, 'stop date')
if dt_stop - timedelta(hours=14) > dt_start:
break