Working with sql connections in which I get a list on return containing 4 specific items for each selection row. I am running into an issue where the print output is different from an output text file.

When I print this list, it looks like it should, no problems.

>>>print(my_list)
>>>['item1', 'item2', 'item3', 'item4', 'item1a', 'item2a', 'item3a', 'item4a']

I added in some labels to print these items with a label for their content description, doing the following:

labels = ['ID1', 'ID2', 'ID3', 'ID4']
my_dictionary = {}
filename = '\\Somefilepath\\file.txt'
len_of_labels = len(labels)

with open(filename, "w", encoding='utf-8') as f:
    for i, l in enumerate(my_list):
        my_dictionary[l] = labels[i % len_of_labels]
    for d in my_dictionary:
        f.write('{:15} : {:3}'.format(my_dictionary[d], d))
f.close()

If I use print instead of f.write, I get the anticipated output of:

ID1      item1
ID2      item2 
ID3      item3
ID4      item4
ID1      item1a
ID2      item2a 
ID3      item3a
ID4      item4a 
# And so one

but when writing to a text file using the above, It is cutting the length off shorter than the len item, and then stopping on the second iteration so it looks something like this:

ID1      item1
ID2      item2 
ID3      item3  
ID1      item1a
ID2      item2a 
# Does not give me all 4 on the first iteration and cuts off the second one

2 Answers

0
Community On Best Solutions

After some testing and review with some help from others, the dictionary became the problem with same key:value pairs. Posting a working way of doing this with the formatting of alignments included.

with open(filename, "w", encoding='utf-8') as f:
    for idx, value in enumerate(my_list):
    i = labels[idx % 3]
    f.write('{:15} : {:3}'.format(i, value))
0
ToddP On

I think it's because you're writing dictionary elements before the dictionary is completely created. Try separating creation and writing like this:

# first create the dictionary
for i, l in enumerate(my_list):
    my_dictionary[l] = labels[i % len_of_labels]

# then write it to file
with open(filename, "w", encoding='utf-8') as f:
    for d in my_dictionary:
        f.write('{:15} : {:3}\n'.format(my_dictionary[d], d))