SimonWho
SimonWho

Reputation: 13

Python - Write a list to several files named with contents of list

I have a list that represents objects which in turn have values YEAR, NAME, NUMBER. Is it possible to then loop through that list of objects, get all values and write that row to a file named with that objects YEAR value?

inData is the list of objects, outPath is just the folder where I want them to go. When I execute the code it seems as if only one line is represented per year. It's like if the next write line overwrites the previous value

Example of code:

def writeFileFromList(inData, outPath) :
    for row in inData:
        outfile = open(str(outPath +"/"+row.getYear(), "w+"))
        outfile.write(str(row) + "\n")
        outfile.close()

Example of what I want in contents of the output file:

2002;AAAAAA;1
2002;BBBBBB;2
2002;CCCCCC;3

Upvotes: 0

Views: 49

Answers (3)

resec
resec

Reputation: 2241

When you open a file, you need to specific the mode you want to use, you can refer to below link for more detail:

https://docs.python.org/2/library/functions.html#open

In your case as you want to append the content into your file of year, you should use 'a' mode to tell python that do not overwrite files, so below is the corrected code base on your example:

def writeFileFromList(inData, outPath) :
    for row in inData:
        outfile = open(str(outPath +"/"+row.getYear(), "a"))
        outfile.write(str(row) + "\n")
        outfile.close()

Upvotes: 0

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

Try this

def writeFileFromList(inData, outPath) :
    for row in inData:
        with open(str(outPath +"/"+row.getYear(), "a")) as outfile:
        outfile.write(str(row) + "\n")

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

To append a line to a file, use

open("filename","a")

Here, a stands for append.

Upvotes: 1

Related Questions