Reputation: 1
I would like to add commas between the elements in the file. Right now it outputs all crammed together. This is part of a larger program. Can anyone help?
code:
def export_emp():
f = open('output.txt','a+')
for i in range (len(employee_List)):
f.write(str(employee_List[i][0]))
f.write(str(employee_List[i][1]))
f.write(str(employee_List[i][2]))
f.write(str(employee_List[i][3]))
f.write(str(employee_List[i][4]))
f.close()
def add_empFile():
output=open('output.txt','r')
file=output.read()
output.close()
print(file)
Upvotes: 0
Views: 79
Reputation: 26039
You can join with comma and write to file at the end:
with open('output.txt','a+') as f:
for x in employee_List:
to_save = ', '.join([str(x[i]) for i in range(5)])
f.write(to_save)
Also, use with open(...)
to open file, so you don't need to worry about closing the file.
Upvotes: 0
Reputation: 171
If you want to add commas between all employee_List, you can just iterate all element in employee_List and use join method to add commas, don't need to specify all index when concatenate them.
def export_emp():
with open('output.txt','a+') as f:
string = ','.join([str(x) for x in employee_List])
f.write(string)
Upvotes: 0
Reputation: 21
You can define a function to add commas in the file:
def write_to_file(file,text):
if text is not None:
file.write(text+",")
Upvotes: 1
Reputation: 33335
Add a comma to the end of the write()
content, like so:
f.write(str(employee_List[i][0]) + ",")
Upvotes: 0