1

I have a list as follows and trying to write it out to a txt file as tab delimited.

final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]

My output statement is but it does not eliminate the square brackets:

fh = open("text.txt", "w")
fh.write('\n'.join('%s %s' % x for x in final_out))
fh.close()

My desired output is:

2893541 OVERALL friendly and genuine.   77 
2893382 SPEED   timely manner.  63

Thank you so much in advance.

3 Answers 3

1
  1. Use with when opening files to automatically clean up your file handles.
  2. You still end up with square brackets because you're converting a list to a string.
  3. You aren't actually using tabs anywhere

My recommendation is to use the csv module, which will also handle escaping for you (by default using quotes).

import csv

final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]

with open('text.txt', 'wb') as fh:
    writer = csv.writer(fh, delimiter='\t')

    for row in final_out:
        writer.writerow(row[0] + [row[1]])
Sign up to request clarification or add additional context in comments.

Comments

0

You can modify the write line like this:

fh.write('\n'.join('%s %s' % (' '.join(a), b) for a, b in final_out))

Comments

0

You can try using this approach:

final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]
fh = open("text.txt", "w")

for final_out_item in final_out:
    first_part = '\t'.join(final_out_item[0])
    fh.write("%s\t%s\n" % (first_part, final_out_item[1]))

fh.close()

1 Comment

Note that the previous code it's not using any other additional libraries given the simplicity of the work done...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.