Mathias
Mathias

Reputation: 648

Pythonic conversion of a string into a CSV-file

I have a string, a very long string which I would like to import into excel for further treatment. The string is in such a form as in the dummy code below. My code is working, doing the job, but I would love to see the pythonic way of handling it since I feel like it is a rather poor non-flexible code.

info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 
23 de 23 de 23 de 23 de 23 de 23 de 23'
info = [x.strip() for x in info.split(" ")]
file = open('testfile.txt','w') 
for i in range (0,len(info),2):
    file.write(info[i]) 
    file.write(",")
    file.write(info[i+1]) 
    file.write("\n") 
file.close() 
print("Done")

The output is supposed to be:

    de, 23
    de, 23
    de, 23

Upvotes: 0

Views: 164

Answers (2)

user3738870
user3738870

Reputation: 1632

Maybe this could be somewhat of an improvement:

info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 
23 de 23 de 23 de 23 de 23 de 23 de 23'

days = info.split()
output_form = "{},{}\n"

with open('testfile.txt','w') as file:
    for i in range (0,len(days),2):
        file.write(output_form.format(days[i],days[i+1]))
print("Done")

Upvotes: 1

Zecong Hu
Zecong Hu

Reputation: 3234

A more compact approach would be:

info = 'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23' +
       'de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23 de 23'
info = info.split()
with open('testfile.txt', 'w') as f:
    f.write('\n'.join(a + ',' + b for a, b in zip(info[::2], info[1::2])))

where info[::2] contain all elements with even indices, and info[1::2] contain all elements with odd indices.

Upvotes: 1

Related Questions