pythonexport-to-text

Python export to a TXT formatted or to Clipboard


I have a csv file that is something like BM13302, EM13203,etc I have to read this from a file then reformat it to something like 'BM13302', 'EM13203',etc

What I'm having problems with is how do I export (write it either the clipboard or a file, I can cut and paste from. This is a tiny little project for reformatting some for part of some SQL code that's given to me in a unclean format and i have to spend a little while formatting it out. I would like to just point python to a directory and past the list in the file and have it export everything that way I need it.

I have the following code working

import os
f = open(r"/User/person/Desktop/folder/file.csv")
csv_f = csv.reader(f)

for row in csv_f:
    print(row)

I get the expected results

I would like find out how to take the list(?) and format it like this 'BM1234', 'BM2351', '20394',....etc and copy that to the clipboard

I thought something doing something like

with open('/Users/person/Desktop/csv/export.txt') as f:
    f.write("open=", + "', '")
f.close()

nothing is printed. Can't find an example of what I'm needing. Anyone able to help me out??

Much Appreciate!


Solution

  • You can have the csv module quote things for you. As far as I know there is no clipboard in the python standard libs but there are various mechanisms out there. Here I'm using pyperclip which is reasonable for text-only copies.

    import pyperclip
    import csv
    import io
    
    def clip_csv(filename):
        outbuf = io.StringIO()
        with open('file.csv', newline='') as infile:
            incsv = csv.reader(infile, skipinitialspace=True)
            outcsv = csv.writer(outbuf, quotechar="'", quoting=csv.QUOTE_ALL)
            outcsv.writerows(incsv)
        pyperclip.copy(outbuf.getvalue())
    
    clip_csv('file.csv')
    # DEBUG: Verify by printing clipboard
    print(pyperclip.paste())