如何遍历列表并将内容添加到文件中

时间:2017-04-28 16:11:18

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

和美好的同事开发者。我想知道是否说我想将列表中的所有内容追加到文本文件中但是。我希望它看起来像这样

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

#the list

正常文件

文本

文件

:d

以及我想做什么

这个东西

是foo

foooo

文字栏

文件bur

:D baar

1 个答案:

答案 0 :(得分:0)

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

示例:

# 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)