Python Forum
write mariadb table rows query to each file? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: write mariadb table rows query to each file? (/thread-32306.html)



write mariadb table rows query to each file? - shams - Feb-02-2021

I want to query table pop and write each row to a deferent file, this is code, but the code write the last row to all three files:
# Create a cursor object 
cur  = conn.cursor() 
query = f"SELECT user, passwd,server FROM pop"
cur.execute(query)
for row in cur:
	list1 = ['1', '2', '3']
	for i in range(len(list1)):
		f = open('mail%s' % i, 'w')  
		print(row[0],row[1],row[2], file=f)



RE: write mariadb table rows query to each file? - buran - Feb-02-2021

you write 3 files for every row, overwriting previous files

cur  = conn.cursor() 
query = "SELECT user, passwd, server FROM pop"
cur.execute(query)
for idx, row in enumerate(cur, start=1):
   with open(f'mail{idx}.txt', 'w') as f:
        f.write(','.join(row))

I added 'w' mode to open - it was mistake on my part