Writing a list of tuples to a text file in Python

后端 未结 6 732
执笔经年
执笔经年 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:51

    No one mentioned simply doing:

    with open('file_name', 'w') as f:
        for tuple in tuples:
            f.write('%s %s %s\n' % tuple)
    

    This has several ups. It's easier to comprehend what you're doing, the format is painfully obvious and easy to modify, and you never forget to use str(object).

    The downside to this compared to the join solutions is if the tuple changes sizes it won't work with one of the following tracebacks:

    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: not all arguments converted during string formatting
    
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: not enough arguments for format string
    

    (Try reproducing them as an exercise.)

    In my opinion if the tuples are not going to be of varying size the most pythonic thing to do is the version presented here.

    import this #and decide for yourself :)
    

    Also, see resources for more info (in order of relevance to the problem):

    http://docs.python.org/library/stdtypes.html#string-formatting-operations

    http://docs.python.org/library/string.html

    http://www.python.org/dev/peps/pep-0292/

提交回复
热议问题