KieranF
KieranF

Reputation: 79

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')

Upvotes: 0

Views: 558

Answers (2)

Jenny
Jenny

Reputation: 661

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).

Upvotes: 2

Yoan B. M.Sc
Yoan B. M.Sc

Reputation: 1505

I haven't worked with tkinter, but PySimplyGUI, which to my knowledge is built on tkinter so you should have the possibility to extract the variables that correspond to the name of the file selected by the user. That's what I'm doing using PySimpleGUIon a similar problem.

Then, extract the file name selected by the user through the prompt and pass it as an argument to your function:

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

Upvotes: 2

Related Questions