У меня есть сценарий Python, который создает CSV-файл с именем 'reader.csv' с запрашиваемыми данными из Salesforce для целей подготовки. Затем он отправляет данные, считывает данные из 'reader.csv' строка за строкой и записывает эту строку в наш выходной файл. Для некоторого контекста необходимо использовать промежуточный файл для манипулирования индексами массива в каждой строке на основе определенных значений, чтобы разместить их в другом месте выходного файла (получение значений даты состояния ипотеки и размещение этой же даты в соответствии с заголовками столбцов). ).
На корпоративном компьютере с Windows 7 сценарий считывает массив из каждой строки в файле 'reader.csv' не по порядку ... что означает, что запись в выходной файл происходит не по порядку. Он был протестирован на нескольких компьютерах Mac, новой машине с Windows 10 и даже Raspberry Pi, работающей на старом дистрибутиве Linux ... и все работает отлично. Тем не менее, когда мы запускаем скрипт на компьютере с Windows 7, он считывает данные из промежуточного файла не по порядку, а затем записывает их по порядку в выходной файл. Вот мой код, который извлекает данные и затем записывает их в соответствующие файлы CSV (наряду с методом преобразования, который я использую для манипулирования словарем:
def sf_extract(sf_object, query):
""" Queries Salesforce objects and returns the data in an
OrderedDict """
# Define the job and object, then query the data
job = sf.create_query_job(sf_object, contentType='CSV')
batch = sf.query(job, query)
sf.close_job(job)
# Waits to make sure the query has been fetched
while not sf.is_batch_done(batch):
time.sleep(10)
# Decode the results
for result in sf.get_all_results_for_query_batch(batch):
data = unicodecsv.DictReader(result, encoding='utf-8')
return data
def csv_writer(sf_object, data):
""" Creates a 'Reader' file, transforms the data, then writes
the transformed data to an output file """
file_name = "contact_product_data " + str(year_month_day) + ".csv"
# Opens a CSV file
with open("reader.csv", 'a+', encoding='utf-8', newline='') as in_file:
# Grabs each item (record dictionary) from the data and loops through it
for item in data:
# Logic to get rid of records that are not owned by Loan Officer's
if item["Owner.Id"] in users_list:
item = data_transform(sf_object, item)
writer = csv.DictWriter(in_file, item.keys())
writer.writerow(item)
with open("reader.csv", 'r+', encoding='utf-8', newline='') as in_file, open(file_name, 'w+', encoding='utf-8', newline='') as out_file:
reader = csv.reader(in_file, delimiter=',')
writer = csv.writer(out_file)
writer.writerow(config.csv_header)
for row in reader:
print(row)
try:
status = row[28]
date = row[29]
if str(status) in config.milestone_keys:
row[config.milestone_index[status]] = str(date)
except:
writer.writerow(row)
else:
writer.writerow(row)
def data_transform(sf_object, item):
""" Take the results of a query job and transform the data
(append
a "Contact Type" header and value, depending on the Salesforce
object). """
item = OrderedDict(item)
if sf_object == "Bank_Account__c":
item["Mortgage_Status_Date__c"] = (item["Mortgage_Status_Date__c"])[:-14]
item.update({'Contact Type':'Client'})
item.move_to_end('Contact Type', last=False)
item.update({'Lead Source':''})
item.move_to_end('Lead Source', last=False)
item.update({'App Received':''})
item.update({'Submitted to Underwriting':''})
item.update({'Initial/Conditional Approval':''})
item.update({'Clear to Close':''})
item.update({'Funded':''})
item.update({'Denied':''})
item.update({'Withdrawn':''})
del item["Owner.Id"]
if item["Opportunity__r.LeadID__c"]:
item["Primary_Customer__r.Id"] = item["Opportunity__r.LeadID__c"]
del item["Opportunity__r.LeadID__c"]
if sf_object == "Lead":
item.update({'Contact Type':'Lead'})
item.move_to_end('Contact Type', last=False)
item.update({'Lead Source':item["LeadSource"]})
item.move_to_end('Lead Source', last=False)
del item["LeadSource"]
del item["Owner.Id"]
if sf_object == "Opportunity":
item.update({'Contact Type':'Lead'})
item.move_to_end('Contact Type', last=False)
item.update({'Lead Source':item["LeadSource"]})
item.move_to_end('Lead Source', last=False)
del item["LeadSource"]
del item["Owner.Id"]
if item["LeadID__c"]:
item["Account.Id"] = item["LeadID__c"]
del item["LeadID__c"]
if sf_object == "Contact":
item.update({'Contact Type':'Referral Source'})
item.move_to_end('Contact Type', last=False)
item.update({'Lead Source':''})
item.move_to_end('Lead Source', last=False)
del item["Owner.Id"]
return item
По какой-то причине он просто не работает на этом компьютере с Windows, и я не могу понять, почему. Это csv.reader (), который принимает массив для каждой строки не по порядку? Мне нужна помощь и быстро.