As title, I’m searching for a method for deleting a row from a csv file, using a tkinter’s treeview GUI.
Basically, I delete a selection with:
def elimina():
with open('/path/to/file.csv', 'a',
encoding='UTF-8') as elenco_aggiornato:
selezione = tree_colonne.selection()[0]
values = tuple(tree_colonne.item(selezione)['values'])
tree_colonne.item(selezione)['values']
tree_colonne.delete(selezione)
…but I noticed that it deletes only graphically the item I select. I tried to create a variable for a csv writer for making a writerow method but I failed.
How can I delete what I select from the GUI to edit the csv file?
Opening a file for 'a' is append, which can only ever add data to it.
This is fine for adding more rows to the end of a CSV file and very
safe.
A CSV file is a text file. The only way to “delete” from it it to
rewrite the file without the rows you no longer want. In the simple case
you rewrite the entire file.
Make a copy of the original contents of the CSV; there’s a fair risk of
destroying your data while experimenting.
I tried different combinations but I can’t understand the way to rewrite the file without the line I chose to delete. My function rewrite the whole file, erasing everything from it or I also obtained a copy of the whole file but with a repeated line that is not my choice.
After the code just posted above, my last attempt was:
Items between parenthesis are referred to a csv.reader method that print the results in a tkinter’s treeview with the ’ insert ’ method.
I also tried to put the treeview’s content in the csv.writerow method but I saw that is not possible.
For sure (as always) it would be a very silly thing to do but I can’t approach to this.
I’m working with the author of pysimplesql. We are very close to releasing a new version that supports loading and deleting lines from a csv file loaded into a PySimpleGUI sg.Table (basically a wrapped tkinter treeview).
Take a look at the Csv example, and if you download, make sure to grab the development branch!