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

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

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

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

Related

When I import an array from another file, do I take just the data from it or need to "build" the array with how the original file build it?

Sorry if the question is not well formulated, will reformulated if necessary.
I have a file with an array that I filled with data from an online json db, I imported this array to another file to use its data.
#file1
response = urlopen(url1)
a=[]
data = json.loads(response.read())
for i in range(len(data)):
a.append(data[i]['name'])
i+=1
#file2
from file1 import a
'''do something with "a"'''
Does importing the array means I'm filling the array each time I call it in file2?
If that is the case, what can I do to just keep the data from the array without "building" it each time I call it?
If you saved a to a file, then read a -- you will not need to rebuild a -- you can just open it. For example, here's one way to open a text file and get the text from the file:
# set a variable to be the open file
OpenFile = open(file_path, "r")
# set a variable to be everything read from the file, then you can act on that variable
file_guts = OpenFile.read()
From the Python docs on the Modules section - link - you can read:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it
This means that importing a module has the same behavior as running it as a regular Python script, unless you use the __name__ as mentioned right after this quotation.
Also, if you think about it, you are opening something, reading from it, and then doing some operations. How can you be sure that the content you are now reading from is the same as the one you had read the first time?

Can I save a Pandas DataFrame with a Tkinter File Dialog?

I am fairly new to programming, and even newer to Tkinter.
I am setting up a GUI that works with an SQL Server to allow front end users to retrieve, update, and delete certain information.
Currently I have everything communicating and working correctly, but I have a function that exports a list of the results into an excel file using Pandas. The export works fine, but it has the static name and directory I give it inside the Pandas to_excel method.
I want to use a Tkinter asksaveasfilename dialog to allow the user to name and choose the files export location, but I can't seem figure out how this works with this dialogue box (if it is even possible). Is there an option inside the dialog boxes code where I specify what information I want to save?
def exportFunc():
pd.DataFrame(data).to_excel("TestList.xlsx", header=False, index = True)
filedialog.asksaveasfilename(initialdir = "/", title = 'Save File', filetypes = ("Excel File", "*.xlsx"))
pass
My code doesn't produce any errors, just simply saves nothing with the dialogue box with everything I try. Right now I have the file dialog commented out in my actual code, but if someone could direct me towards a possible solution, I would be grateful!
10 months ago this was posted, but I hope this answer can help a fellow novice googling around for this answer as well.
How I solved this was noticing the asksaveasfile function outputs a value that contains the user specified file path and file name. For example:
< closed file u'E:Filepath/AnotherPath/work2.xlsx', mode 'w' at 2119x6710 >
I then used regex and the replace method to strip away all values surrounding the filepath, which once finished, the to_excel function would see as a hardcode.
Hope this helps someone out there!
out = tkFileDialog.asksaveasfile(mode='w', defaultextension=".xlsx")
out.close()
restr = str(out)
RegexPrep = restr.replace("'w'", '')
outRegex = re.findall(r"'(.*?)'", RegexPrep)
ToExcelRegex = str(outRegex)
MorePrep = ToExcelRegex.replace("[",'')
MorePrep = MorePrep.replace("]",'')
MorePrep = MorePrep.replace("'",'')
Final = MorePrep.strip()
find.to_excel(Final, index=False)
Asksavasafile returns a file object, so we can use that to save the df.
from tkinter import filedialog, Tk
import pandas as pd
df = pd.DataFrame(
{"Test": range(20)}
)
root = Tk() # this is to close the dialogue box later
try:
# with block automatically closes file
with filedialog.asksaveasfile(mode='w', defaultextension=".xlsx") as file:
df.to_excel(file.name)
except AttributeError:
# if user cancels save, filedialog returns None rather than a file object, and the 'with' will raise an error
print("The user cancelled save")
root.destroy() # close the dialogue box

How to extract all variable and their value from a python script with location like "C:\\Users\\SomeFolder\\PythonFile.py"?

I am working on a text editor made with python and i want to add a feature of Variable Explorer in my editor I am not able to extract the variable values from a python file. My basic working principle is that my program takes location of the current edited file and try to import it but I am not able to import because that is string not an object. It is bit confusing so let me show the code.
fileName='C:\Users\Project.py'
class varExplorer:
def ShowVarList(editfile):
editfile.replace('\','.')
editfile.replace('.py','')
editfile.replace(':','')
# so the file path will be like C.Users.Project
import editfile # the problem
print(editfile.__dict__)# here i will get dictionary of values
varExplorer.ShowVarList(fileName)
help taken for dict
print(editfile.__dict__)
from
I want to extract all the variable names with a python script, from a python file, without editing the python file
The main problem is that it cannot import from a string
import editfile # the problem
because it is a string and import does not take strings
So I want a function which can print all the variable and their values from a specific python file from any location.
Use importlib
import importlib
importlib.import_module(editfile)
Also be careful, str is immutable in Python, replace returns a new string and does not modify its argument.
So you get:
import importlib
class VarExplorer:
def show_var_list(editfile):
editfile = editfile.replace('\\','.')
editfile = editfile.replace('.py','')
editfile = editfile.replace(':','')
# so the file path will be like C.Users.Project
module = importlib.import_module(editfile) # the solution
print(vars(module))

Phonebook in Python

I am writing a test console program-phonebook with Python. My IDE is JetBrains PyCharm. I have 5 functions - Search contact, Enter contact, Delete contact, All phones and Exit. My question is how can I make the program to save information in text file and when I compile it, the information will be saved in this text file ?
You could write the data to a csv file. https://docs.python.org/3/library/csv.html
This should help : https://docs.python.org/2/tutorial/inputoutput.html
I think for your case the easiest would be to write data to a python file as follows:
with open('PathToAFile/MyFile.py', 'w') as f:
f.write('contact_names =[' + contact_name1 + ',' + contact_name2... + ']\n')
This will make it extremely easy to load data later without having to parse (as in a csv).
In the example code i provide, im saving your contact names to a list called 'contact_names' in a python file named 'MyFile.py'. When you execute 'MyFile.py
you will have access to the 'contact_names' variable

Open URL stored in a csv file

I'm almost an absolute beginner in Python, but I am asked to manage some difficult task. I have read many tutorials and found some very useful tips on this website, but I think that this question was not asked until now, or at least in the way I tried it in the search engine.
I have managed to write some url in a csv file. Now I would like to write a script able to open this file, to open the urls, and write their content in a dictionary. But I have failed : my script can print these addresses, but cannot process the file.
Interestingly, my script dit not send the same error message each time. Here the last : req.timeout = timeout
AttributeError: 'list' object has no attribute 'timeout'
So I think my script faces several problems :
1- is my method to open url the right one ?
2 - and what is wrong in the way I build the dictionnary ?
Here is my attempt below. Thanks in advance to those who would help me !
import csv
import urllib
dict = {}
test = csv.reader(open("read.csv","rb"))
for z in test:
sock = urllib.urlopen(z)
source = sock.read()
dict[z] = source
sock.close()
print dict
First thing, don't shadow built-ins. Rename your dictionary to something else as dict is used to create new dictionaries.
Secondly, the csv reader creates a list per line that would contain all the columns. Either reference the column explicitly by urllib.urlopen(z[0]) # First column in the line or open the file with a normal open() and iterate through it.
Apart from that, it works for me.

Categories

Resources