У меня есть Python скрипт, который конвертирует файлы из формата DBF в CSV. Проблема, с которой я столкнулся, заключается в том, что во время работы скрипта я потерял соединение с сетевым диском, содержащим каталог и файлы, которые мне нужно преобразовать. Вместо того, чтобы начинать задачу заново, я бы хотел продолжить с того места, где остановился. По сути, у меня возникли небольшие проблемы при редактировании моего сценария, чтобы проверить совпадения имен файлов в двух каталогах (один, содержащий файлы, которые мне нужно преобразовать, и каталог назначения с преобразованными файлами), а затем выполнить преобразование, если нет совпадения. найден. Имена файлов совпадают, за исключением расширения .DBF , удаленного из имени (например, «A0000001.DBF» <- исходный файл в «A0000001.csv», «A0000002.DBF» <- исходный файл TO 'A0000002.csv', et c.) </p>
Ниже приведен мой код:
import os
import re
import multiprocessing
from dbfread import DBF
import pandas as pd
in_dir = 'Y:\\Directory_with_files_to_convert\\'
out_dir = 'C:\\Destination_Directory_with_converted_files'
in_file_list = os.listdir(in_dir) #store target directory files in a list
out_file_list = os.listdir(out_dir) #store destination directory files in a list
pattern = re.compile(r'A\d\d\d\d\d\d\d|AB\d\d\d\d\d\d|B\d\d\d\d\d\d\d')
match_1 = re.findall(pattern, str(in_file_list)) #match all file names in the target directory
match_2 = re.findall(pattern, str(out_file_list)) #match all file names in the destination directory
matches = set(match_1).intersection(match_2) #join the lists together so a comparison can be made
srt_match = sorted(matches) #sort matches in numerical order
'''Here is where I am having trouble.
How can I edit the code below so that if it does not find a matching file name in the destination directory,
it will pull the next file in the target directory and convert it?
In case I happen to lose the connection to the network drive again,
I can run this script and pick up where I left off.'''
for match in srt_match: #iterate through the sorted matches
if match != srt_match: #if no match is found, convert the next file in the target directory
for file in in_file_list: #loop through the target directory and obtain next file to convert
print(f'\nReading in {file}...')
dbf = DBF(file)
dbf.encoding = 'utf-8'
dbf.char_decode_errors = 'ignore'
print('\nConverting to DataFrame...')
df = pd.DataFrame(iter(dbf))
df.columns.astype(str)
print(df)
print('\nWriting to CSV...')
dest_directory = 'C:\\Destination_Directory\%s.csv' % ('A' + file.strip('.DBF'))
df.to_csv(dest_directory, index = False)
print(f'\nConverted {file} to CSV. Moving to next file...')
else:
print('All files converted.')
У меня также импортирован многопроцессорный модуль, хотя он не используется. Я хотел бы включить это и в эту задачу, поскольку в нем более 10 000 файлов, и, возможно, его можно будет выполнить быстрее на нескольких ядрах ЦП; Тем не менее, я не хочу просить слишком много в одном посте (хотя, если вы склонны предлагать рекомендации, спасибо).
Спасибо всем за любую помощь.