【问题标题】:How to iterate through a list and add the contents to a file如何遍历列表并将内容添加到文件中
【发布时间】:2017-04-28 16:11:18
【问题描述】:

祝各位开发者好。我想知道是否说我想将列表中的所有内容附加到文本文件中,但是。我希望它看起来像这样

list = ['something','foo','foooo','bar','bur','baar']

#the list

普通文件

这个

文字

文件

:D

以及我想做什么

这个东西

是傻

傻瓜

文本栏

文件 bur

:D 巴尔

【问题讨论】:

    标签: python-2.7 list text-files text-manipulation


    【解决方案1】:

    这可以通过读取原始文件的内容并将添加的单词附加到每一行来完成

    示例:

    # changed the name to list_obj to prevent overriding builtin 'list'
    list_obj = ['something','foo','foooo','bar','bur','baar']
    path_to_file = "a path name.txt"
    
    # r+ to read and write to/from the file
    with open(path_to_file, "r+") as fileobj:
        # read all lines and only include lines that have something written
        lines = [x for x in fileobj.readlines() if x.strip()]
        # after reading reset the file position
        fileobj.seek(0)
        # iterate over the lines and words to add
        for line, word in zip(lines, list_obj):
            # create each new line with the added words
            new_line = "%s %s\n\n" % (line.rstrip(), word)
            # write the lines to the file
            fileobj.write(new_line)
    

    【讨论】:

    • 谢谢。我很快就尝试了,考虑先在文本文件上写第一列以使事情变得容易。谢谢你
    猜你喜欢
    • 2021-03-09
    • 2017-05-19
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多