Python Forum
save content of table into file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
save content of table into file
#1
hi;
I want to save the content of the table of my sqlite database into file (text, or pdf , or csv)
for text file I proceed like that but it was not worked :

def createFileFromLoc35R(self):

    conn = sqlite3.connect (ils35R.db')
    curseur=conn.cursor()
# loc35R table of the ils35R database :			
    c=curseur.execute("SELECT * FROM loc35R")
				  
    listeTableLoc35R=c.fetchall()

    f=open("guru99.txt", "a+")

    for readData in listeTableLoc35R :
	    f.write(readData)
	    f.write("\n")
    f.close()
Reply
#2
atlass218 Wrote:I proceed like that but it was not worked :
What happened? Did python write an error message? Did it write a file?
Reply
#3
Hi; I modify my function like that :

	def reateFileFromLoc35R(self):
		script_path_ils35R = os.path.dirname(os.path.realpath(__file__))#récupérer le répertoire courant
		new_path_ils35R=script_path_ils35R + '\\data_base'  #concaténer au path ci-dessus  le path du dossier data_base
		os.makedirs(new_path_ils35R, exist_ok=True)   #creer le dossier data_base au nouveau path
	
		
		conn = sqlite3.connect (new_path_ils35R+'\\ils35R.db')
		curseur=conn.cursor()			
		c=curseur.execute("SELECT * FROM loc35R")
				  
		listeTableLoc35R=c.fetchall()

		f=open("guru99.txt", "a+")

		for readData in listeTableLoc35R :
			f.write(readData[0])
			f.write("\n")
        
		f.close()
		print("ceci est l'operation de sauvegarde dans un fichier texte")
			
when I execute the function by clicking on the button :
the sentence : ceci est l'operation de sauvegarde dans un fichier texte
appear at the bottom of my editor but I don't find the text file at the directory that containt my index.py
Reply
#4
Is there a reason you open file with "a+" if you only want to write to it?
To write to the dir where the .py file was started use first line.
To handle reading/writing files use "with" command.
To create output to write to file use f-strings (available since Python 3.6)
local_dir = os.path.dirname(__file__)
with open(os.path.join(local_dir, "guru99.txt"), "w") as file:
    for data in listeTableLoc35R:
        file.write(f'{data[0]}\n')
Reply
#5
Hi; thank you for the answer ; I will test your code.
I made the mode "a" instead of "w" during the writing in the text file in order to save the information contained in this same file
I want all new information added to the contents of the file without overwriting the information that already exists in this file
Reply
#6
I use this code to create a text file and save in the database information

conn = sqlite3.connect (new_path_ils35L+'\\ils35L.db')
curseur=conn.cursor()			
c=curseur.execute("SELECT * FROM gp35L")
                        
listeTablegp35R=c.fetchall()

local_dir = os.path.dirname(__file__)
	with open(os.path.join(local_dir, "filesave/gp35L.txt"), "w",encoding="utf-8") as file_gp35L:
		for data in listeTablegp35L:
			for k in range(10) :
				file_gp35L.write(f'{data[k]}\t')
			file_gp35L.write("\n")
unfortunately the information from the database is badly arranged following the columns

[Image: lcfq.png]

I need help to resolve this problem
thanks
Reply
#7
(Aug-23-2019, 12:12 PM)atlass218 Wrote: unfortunately the information from the database is badly arranged following the columns
How should it be arranged?
Reply
#8
I have already managed to display the contents of the database in a pyqt5 widget table, see the image below:
[Image: qsap.jpg]
I would like in my text file the columns are arranged as on this picture
Reply
#9
You can use a specialized module such as ptable
Reply
#10
the paragraph to import information data from a database cursor to the prettytable,there is the command :
mytable = from_cursor(cursor)
does not work and creates an error.
at one video in youtube I remark that I must write it like that : mytable = from_db_cursor(cursor)

my final works now correctely
after installing prettytable by : pip install PTable

and :

from prettytable import from_db_cursor
#Fonction pour creer un fichier texte et sauvegarder dedans le contenu de la bdd :
def create_file_from_loc35R(self):

	script_path_ils35R = os.path.dirname(os.path.realpath(__file__))#récupérer le répertoire courant
	new_path_ils35R=script_path_ils35R + '\\data_base'  #concaténer au path ci-dessus  le path du dossier data_base
	os.makedirs(new_path_ils35R, exist_ok=True)   #creer le dossier data_base au nouveau path

	script_path_filesave_loc35R = os.path.dirname(os.path.realpath(__file__))#récupérer le répertoire courant
	new_path_filesave_loc35R=script_path_filesave_loc35R + '\\filesave'  #concaténer au path ci-dessus  le path du dossier data_base
	os.makedirs(new_path_filesave_loc35R, exist_ok=True)   #creer le dossier data_base au nouveau path
        
	try:

		conn = sqlite3.connect (new_path_ils35R+'\\ils35R.db')
		curseur=conn.cursor()			
		c=curseur.execute("SELECT * FROM loc35R")
							
		mytable = from_db_cursor(c)
		table_txt = mytable.get_string()

		local_dir = os.path.dirname(__file__)
			with open(os.path.join(local_dir, "filesave/loc35R.txt"), "w",encoding="utf-8") as file_loc35R:
				file_loc35R.write(table_txt)
        
	except :
		self.messageInfo_filesave()
there is the output text file :

[Image: dt7g.jpg]

thanks for the link of the prettytable
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copy xml content from webpage and save to locally without special characters Nik1811 14 980 Mar-26-2024, 09:28 AM
Last Post: Nik1811
  Open/save file on Android frohr 0 339 Jan-24-2024, 06:28 PM
Last Post: frohr
  how to save to multiple locations during save cubangt 1 564 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  save values permanently in python (perhaps not in a text file)? flash77 8 1,250 Jul-07-2023, 05:44 PM
Last Post: flash77
  Save and Close Excel File avd88 0 3,084 Feb-20-2023, 07:19 PM
Last Post: avd88
  Save multiple Parts of Bytearray to File ? lastyle 1 963 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Use module docx to get text from a file with a table Pedroski55 8 6,201 Aug-30-2022, 10:52 PM
Last Post: Pedroski55
  Extracting Specific Lines from text file based on content. jokerfmj 8 3,046 Mar-28-2022, 03:38 PM
Last Post: snippsat
Sad Want to Save Print output in csv file Rasedul 5 10,993 Jan-11-2022, 07:04 PM
Last Post: snippsat
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,286 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B

Forum Jump:

User Panel Messages

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