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?
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"
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)
you write 3 files for every row, overwriting previous files

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

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can't write to file Mark17 2 94 Sep-24-2021, 03:45 PM
Last Post: Mark17
  How to write in text file - indented block Joni_Engr 3 343 Aug-09-2021, 06:30 PM
Last Post: deanhystad
  Error using mariadb select query with form in python? shams 2 323 Jul-29-2021, 12:30 PM
Last Post: shams
  Partial Matching Rows In Pandas DataFrame Query eddywinch82 1 352 Jul-08-2021, 06:32 PM
Last Post: eddywinch82
  Read and write active Excel file euras 4 536 Jun-29-2021, 11:16 PM
Last Post: Pedroski55
Lightbulb [Solved] df.loc: write data in certain rows ju21878436312 1 387 Jun-28-2021, 06:49 AM
Last Post: ju21878436312
  Read file, reformat and write new file bryanmartin113 1 517 Jun-08-2021, 09:27 PM
Last Post: Larz60+
  Pandas DataFrame combine rows by column value, where Date Rows are NULL rhat398 0 493 May-04-2021, 10:51 PM
Last Post: rhat398
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 1,812 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Yahoo_fin, Pandas: how to convert data table structure in csv file detlefschmitt 14 2,396 Feb-15-2021, 12:58 PM
Last Post: detlefschmitt

Forum Jump:

User Panel Messages

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