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
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 727 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Yahoo_fin, Pandas: how to convert data table structure in csv file detlefschmitt 14 931 Feb-15-2021, 12:58 PM
Last Post: detlefschmitt
  Read/Write binary file deanhystad 3 318 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  Running A Parser In VSCode - And Write The Results Into A Csv-File apollo 5 508 Jan-14-2021, 08:58 PM
Last Post: snippsat
  Duplicating Rows And Put Them In Certain Index Position Query eddywinch82 0 220 Nov-25-2020, 05:24 PM
Last Post: eddywinch82
  Fetch Oracle DB rows & print it in HTML file with table's col headers in table format tssr_2001 1 665 Sep-04-2020, 01:39 PM
Last Post: ibreeden
  How do I write a single 8-bit byte to a file? MysticLord 2 571 Sep-03-2020, 12:27 PM
Last Post: MysticLord
  Appending some rows in a .csv file from another .csv file tester_V 1 404 Aug-26-2020, 01:04 AM
Last Post: tester_V
  unable to write to log file Mekala 2 523 Aug-12-2020, 11:02 PM
Last Post: Mekala
  List Won't Write in Text File IILawrenceII 4 585 Jul-17-2020, 11:16 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

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