Reputation: 861
I have this function that takes a list and prints it out to an outfile:
def writeToFile(files):
for path2 in files:
fi= open(fileo, 'w')
fi.truncate()
fi.write('\n' + str(foundFiles2))
fi.close()
foundFiles2 = [
'bb.TechnicalDefinition.UnitTests.vbproj'
'bb.Units.UnitTests.vbproj'
'bb.Utilities.UnitTests.vbproj'
'bb.Visualization.UnitTests.vbproj' ]
It prints to the file no problem however I want it to print a new line after every tuple in the list. However, when it write to the file it looks like this:
'bb.APDS.UnitTests.vbproj', 'bb.DatabaseAPI.UnitTests.vbproj', 'bb.DataManagement.UnitTests.vbproj',
I thought the
fi.write('\n' + str(foundFiles2))
would print out each tuple separately on a new line but it doesn't. Do I need a loop in here somewhere or is my syntax just plain wrong?
Upvotes: 1
Views: 73
Reputation: 3217
Open the file before the for
loop and close the file after the for loop ( or use with
like ashwini suggested because it automatically does that.)
The way you are going at it, it will only write the same foundFiles2
list over and over again depending on how many indexes are in files
.
If foundFiles2
is the list you want to iterate over then you need to use it in the for
statement:
for item in foundFiles2:
fi.write(item+'\n')
this will go to the first item, and then write it, and then the second item and then write it etcetera.
Upvotes: 1
Reputation: 251166
You should iterate over the list instead of printing it's str
version.
>>> lis = [1,2,3]
>>> str(lis) #str just returns a string representation of the string
'[1, 2, 3]'
>>> for x in lis : #use for loop to iterate over individual items of the list
... print x
...
1
2
3
your code:
for path2 in files:
#"w" mode automatically truncates the file for you
# Always use `with` statement for handling files, it automatically
# closes the file.
with open(fileo,"w") as f:
for text in foundFiles2: #iterate over each value in the list
f.write(text+"\n")
Upvotes: 1