0

and good day fellow developers. I was wondering if say i would like to append every thing on list to a text file but. i want it to look like this

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

#the list

THE NORMAL FILE

this

is

the

text

file

:D

AND WHAT I WOULD LIKE TO DO

this something

is foo

the foooo

text bar

file bur

:D baar

Skrmnghrd
  • 558
  • 4
  • 10

1 Answers1

0

This can be accomplished by reading the original file's contents and appending the added words to each line

example:

# 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)
user2682863
  • 3,097
  • 1
  • 24
  • 38
  • thanks. im trying this soon, thought about writing the first column on a text file first to make things easy. thankyou – Skrmnghrd May 01 '17 at 13:34