Writing a list of tuples to a text file in Python

后端 未结 6 776
执笔经年
执笔经年 2021-01-05 14:11

I have a list of tuples in the format:

(\"some string\", \"string symbol\", some number)

For example, (\"Apples\", \"=\", 10).

6条回答
  •  感动是毒
    2021-01-05 14:42

    list_of_tuples = [('Apples', '=', 10), ('Oranges', '<', 20)]
    f = open('file.txt', 'w')
    for t in list_of_tuples:
        line = ' '.join(str(x) for x in t)
        f.write(line + '\n')
    f.close()
    

    Given a list of tuples, you open a file in write mode. For each tuple in the list, you convert all of its elements into strings, join them by spaces to form the string, and write the string with a new line to the file. Then you close the file.

    Edit: Didn't realize you started off with a list of tuples. Made changes to reflect that.

提交回复
热议问题