Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python convert.txt to .csv without having a specific file name

I am currently working on an application that will convert a messy text file full of data into an organized CSV. It currently works well but when I convert the text file to csv I want to be able to select a text file with any name. The way my code is currently written, I have to name the file "file.txt". How do I go about this?

Here is my code. I can send the whole script if necessary. Just to note this is a function that is linked to a tkinter button. Thanks in advance.

def convert():
df = pd.read_csv("file.txt",delimiter=';')
df.to_csv('Cognex_Data.csv')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try defining your function as follow:

def convert(input_filename, output_filename='Cognex_Data.csv'):
    df = pd.read_csv(input_filename, delimiter=';')
    df.to_csv(output_filename)

And for instance use it as follow:

filename = input("Enter filename: ")
convert(filename, "Cognex_Data.csv")

You can also put "Cognex_Data.csv" as a default value for the output_filename argument in the convert function definition (as done above).

And finally you can use any way you like to get the filename (for instance tkinter.filedialog as suggested by matszwecja).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading