Python Forum
write mariadb table rows query to each file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write mariadb table rows query to each file?
#1
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)
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Last record in file doesn't write to newline gonksoup 3 366 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 1,375 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,316 Nov-09-2023, 10:56 AM
Last Post: mg24
  How do I read and write a binary file in Python? blackears 6 6,021 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  python script for inserting rows into hbase table lravikumarvsp 7 7,013 Mar-24-2023, 04:44 AM
Last Post: parth_botadara
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,048 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,502 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,178 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  write json into a table herobpv 4 1,424 Jan-22-2023, 04:36 AM
Last Post: herobpv
  how to read txt file, and write into excel with multiply sheet jacklee26 14 9,525 Jan-21-2023, 06:57 AM
Last Post: jacklee26

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020