Python Forum

Full Version: saving text file by FileDialog option
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
this is not a question that i want the code ready, but i'm new to python, and i'm trying to improve my knowledge on the net.
about my code, i just changed it for a more readable appearance of the text file.

def create_file_from_tablewidget(self):
  
    header = []
    lenght=12
    for column in range(self.tableWidget.columnCount()):      
        h = self.tableWidget.horizontalHeaderItem(column).text()
        header.append(h+'\t')
                  
    path,_ = QFileDialog.getSaveFileName(
        self, 'Save File', '', 'CSV(*.txt)')
    if path:
        with open(path, 'w',encoding="utf-8")  as stream:
            writer = csv.writer(stream, delimiter='\t')
            writer.writerow(header)
            for row in range(self.tableWidget.rowCount()):
                rowdata = []
                for column in range(self.tableWidget.columnCount()):
                    item = self.tableWidget.item(row, column)
                    if item is not None:
                        rowdata.append(item.text()+" " * (lenght - len(item.text())))
                    else:
                        rowdata.append('')
                writer.writerow(rowdata)
there is the new apparence of the text file :

[Image: i7ts.jpg]
Well that does look nicer -- and if you can remove those unnecessary quotes at the top it would look even nicer... if you want to put those | and - in as you had shown in the other that would be pretty easy to do with the methodology (pseudo-code) I outlined. So no questions about that methodology then?
hi;
I remove the '\' character and replace it by ' ' at the line 7 of the code.
header.append(h+'           ')
the new appearance of the text file :

[Image: asl0.jpg]
You can write your table to a tab delimited csv, for example "/tmp/test.csv" then (change expandtabs(32) to your needs)

infile = "/tmp/test.csv"
outfile = "/tmp/test.txt"

with open(infile, 'r') as stream:
    text = stream.readlines()
    with open(outfile, 'w') as f:
        for line in text:
            print (line.expandtabs(32), end = "", file=f)
thanks for your help
Pages: 1 2