So my my problem is that I'm running a program once it has finished base functions a pop up box appears asking the user if they would like to save file, if 'yes' then a save dialog box appears. Because the data I'm saving is a dict value I'm receiving an Error from tkinter. I have attempted to use the ".csv" extension as a save point as i read somewhere that dict's can be saved to them, but i'm either going about this wrong way or there is an issue within my code.
Updated Code and explanation why below
Original snippet of code:
def flag_detection():
total_count = Counter(traffic_light)
total_count.keys()
for key, value in total_count.items():
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialfile'] = 'myfile.csv'
if EWT == 'yes':
savename = asksaveasfile(file_opt, defaultextension=".csv")
savename.write(key, ':', value)
Error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:/Users/Lewis Collins/PycharmProjects/program_06.01.17/Home.py", line 108, in run_language_model
main.flag_detection()
File "C:\Users\Lewis Collins\PycharmProjects\program_06.01.17\main_code\main.py", line 179, in flag_detection
savename = asksaveasfile(file_opt, defaultextension=".csv")
File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\filedialog.py", line 423, in asksaveasfile
return open(filename, mode)
TypeError: open() argument 2 must be str, not dict
Because of Tkinter throwing back that it can not save a dict to file i tried the below solution of converting the dict to a str which has also caused problems
Code Snippet of Function attempt to convert to str for tkinter:
def flag_detection():
total_count = Counter(traffic_light)
total_count.keys()
for key, value in str(total_count.items()):
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialfile'] = 'myfile.csv'
if EWT == 'yes':
savename = asksaveasfile(file_opt, defaultextension=".csv")
savename.write(key, ':', value)
So I've updated my code to try and use the str(total_count.items()): to convert to dict as i didn't quite understand the json and pickle libraries after reading them they seemed to complicated for what i needed which is a simple output to a file for a user to be able to go and view.
I am now receiving this Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:/Users/Lewis Collins/PycharmProjects/program_05.0.17/Home.py", line 108, in run_language_model
main.flag_detection()
File "C:\Users\Lewis Collins\PycharmProjects\program_05.0.17\main_code\main.py", line 169, in flag_detection
for key, value in str(total_count.items()):
ValueError: not enough values to unpack (expected 2, got 1)
Any suggestions or feedback is welcome, Thanks in advance.
The first problem is this line:
savename = asksaveasfile(file_opt, defaultextension=".csv")
That is simply not how to call asksaveasfile. asksaveasfile doesn't take a dictionary as its first argument. You should call it this way if you want to use the options in file_opt1:
savename = asksaveasfile(defaultextension=".csv", **file_opt)
When you fix that, the next problem is where you try to write with this statement:
savename.write(key, ':', value)
You get this error message: TypeError: write() takes exactly 1 argument (3 given). It means exactly what it says: you need to provide a single argument rather than three arguments. You can solve that by giving write exactly 1 argument:
savename.write("%s: %s" % (key, value))
However, if all you want to do is save a dictionary to a file, the json module makes this quite easy, without having to iterate over the values.
To save as json, change your flag_detection method to look like this:
import json
...
def flag_detection():
total_count = Counter(traffic_light)
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.json')]
options['initialfile'] = 'myfile.json'
if EWT == 'yes':
savefile = asksaveasfile(defaultextension=".json", **file_opt)
json.dump(total_count, savefile)
If you want to save as a csv file, read the documentation on the DictWriter class which works in a similar way.
Related
i am using streamlit with python in order to allow user to upload multiple files than to show the content as a dataframe.
But first i need to check if its csv type or xls, and dislay the type and name.
The problem is that when it comes to check what is the file type it crash and display the below error:
AttributeError: 'list' object has no attribute 'name'
Traceback:
File "F:\AIenv\lib\site-packages\streamlit\script_runner.py", line 333, in _run_script
exec(code, module.__dict__)
File "f:\AIenv\streamlit\app2.py", line 766, in <module>
main()
File "f:\AIenv\streamlit\app2.py", line 300, in main
file_details = {"filename":data.name,
Note if i upload a single file the script run with no error.
code:
import streamlit as st
import pandas as pd
def main():
if st.sidebar.checkbox("Multiple Files"):
data = st.sidebar.file_uploader('Multiple Excel files', type=["csv","xlsx","xls"],
accept_multiple_files=True)
for file in data:
file.seek(0)
elif st.sidebar.checkbox("Single File"):
data = st.sidebar.file_uploader("Upload Dataset",type=["csv","xlsx","xls"])
if data is not None:
# display the name and the type of the file
file_details = {"filename":data.name,
"filetype":data.type
}
st.write(file_details)
if __name__=='__main__':
main()
You are trying to access name and type of list of files if "multiple files" is checked. I suggest unifying of your 'data' structure and making it always a list. Then you have to iterate over it:
import streamlit as st
import pandas as pd
def main():
if st.sidebar.checkbox("Multiple Files"):
data = st.sidebar.file_uploader('Multiple Excel files', type=["csv","xlsx","xls"],
accept_multiple_files=True)
for file in data:
file.seek(0)
elif st.sidebar.checkbox("Single File"):
data = st.sidebar.file_uploader("Upload Dataset",type=["csv","xlsx","xls"])
if data is not None:
data = [data]
if data is not None:
for file in data:
# display the name and the type of the file
file_details = {"filename":file.name,
"filetype":file.type
}
st.write(file_details)
if __name__=='__main__':
main()
data in this case should be a list type (you can check with type(data)).
What you could do is change:
if data is not None:
# display the name and the type of the file
file_details = {"filename":data.name,
"filetype":data.type
}
st.write(file_details)
To:
if data is not None and len(data) > 0:
st.write("filename {} | filetype: {}".format(data[i].name, data[i].type) for i in range(len(data)))
this is the code I'm working on
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre
remote_conn_pre.connect(ip,
username=username,password=password,look_for_keys=False,allow_agent=False)
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(1002)
remote_conn.send("\n")
remote_conn.send("enable\n")
remote_conn.send("show ip int brief\n")
remote_conn.close()
time.sleep(2)
output = remote_conn.recv(65535)
print output
output_cap = tempfile.TemporaryFile(output)
print output_cap
the output I got was:
Traceback (most recent call last):
File "p1.py", line 27, in <module>
output_cap = tempfile.TemporaryFile(output)
File "/usr/lib/python2.7/tempfile.py", line 488, in TemporaryFile
return _os.fdopen(fd, mode, bufsize)
ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not '
R1#enable
R1#show ip int brief
Interface IP-Address OK? Method Status
Protocol
FastEthernet0/0 192.168.2.101 YES other up
up '
how can I pass the output I can get from my code into a temporary file?
tempfile.TemporaryFile()'s first parameter is mode, not the data you want to write.
To write to a file
fo = open("filename.txt", wb)
fo.write(output)
fo.close()
mode "wb" writes the file in binary, creating a new file if it doesn't already exist, and overwrites the file if it does exist.
I'm making a program that takes two file comparing them then find the percentage of similarity,now I'm having hard time to take the file name THEN Pass IT TO open function to read it THEN PASSING THE DATA Generated into another function ,it shows me that error
IOError: [Errno 22] invalid mode ('r') or filename: ''
my code is
Copied_File = ''
def Click_Copy():
global Copied_File
Copied_File = tkFileDialog.askopenfilename(initialdir='C:/Users/%s' % user)
directory = os.path.split(Copied_File)[0]
return Copied_File
with open((Copied_File), 'r')as file_1:
file1_data = file_1.read()
View_copied_File.insert(0.0, file1_data)
btn_Copy = ttk.Button(text="Open Copied File",command=Click_Copy)
btn_Copy.place(x =10, y = 30, width=120, height=34)
View_copied_File= ScrolledText(Window_1, width=50, height=40,state = "normal")
View_copied_File.place(x =10, y = 70)
As #Stefans commented you, there is a problem when you tried to open the file Copied_File because by the moment you run the with open((Copied_File), 'r')as file_1:, you have Copied_File =.
This means:
with open((Copied_File), 'r')as file_1: is equal to with open('', 'r')as file_1:
You defined Click_Copy() method but you never executed it. So you need to call that method before the with statement.
To resolve your problem, you may call the method directly:
...
with open(Click_Copy(), 'r') as file_1:
...
When i run this code i get an error saying the file does not exist, i have created the file and linked back to them by copying the directory from the save part. I can also see the file and have triple checked the name etc but it still won't work can someone help.
from tkinter import *
import os.path
master= Tk()
master.geometry('500x500+0+0')
def print_value(val):
print ("c1="+str (c1v.get()))
print ("c2="+str(c2v.get()))
c1v=DoubleVar()
c2v=DoubleVar()
c1 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c1v)
c1.grid(row=1,column=1)
c2 = Scale(master, from_=255, to=0, length =400,width =100, troughcolor = 'blue',command=print_value, variable =c2v)
c2.grid(row=1,column=2)
def func():
pass
file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt")
val1, val2 = (x.split("=")[1] for x in file1)
c1.set(val1)
c2.set(val2)
file1.close()
def record():
save_path = 'C:/Users/Josh Bailey/Desktop/pi_dmx'
name_of_file = ("preset_test ")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName , "w")
toFile = ("c1="+str (c1.get())+ "\n""c2="+str(c2.get()))
file1.write(toFile)
file1.close()
master.mainloop()
rec=Button(master, text="Record",width=20, height=10, bg='Red', command=record)
rec.grid(row=2, column=1)
load=Button(master, text="Load",width=20, height=10, bg='gold',command=func)
load.grid(row=2, column=2)
the error is-
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python33\lib\idlelib\run.py", line 121, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "C:\Python33\lib\queue.py", line 175, in get
raise Empty queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args) File "C:\Users\Josh Bailey\Desktop\save test.py", line 24, in func
file1 = open("C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt") FileNotFoundError: [Errno 2]
No such file or directory: 'C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt'
Inside func, you specify the filepath as being:
C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test.txt
However, your record function makes it to be:
C:/Users/Josh Bailey/Desktop/pi_dmx/preset_test .txt
# Note the extra space here--^
Because of this, Python will not be able to find the file.
To fix the problem, remove the space on this line in record:
name_of_file = ("preset_test ")
# here--^
Now record will create the filepath to be what it should.
Also, that pass inside of func should not be there. It does nothing.
You're on Windows right? Replace the slashes with backslashes, \, and add a "r" infront of the string, like this:
file1 = open(r"C:\Users\Josh Bailey\Desktop\pi_dmx\preset_test.txt")
Hope this works
Hello this is a problem I am having. The following program doesn't allow me to take in multiple outplane data but it allow to take in multiple in plane data according to the function in call_Controller. Is there something wrong with the program?
you can try by creating this 4 text file in a folder.
run the program and press Clt to take in both hello.txt and bye.txt
follow by hello1.txt and bye1.txt and you will know the error
somebody please help me with this problem..
hello.txt | hello1.txt
bye.txt | bye1.txt
Error Message:
Traceback (most recent call last):
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 100, in <module>
Name = call_Controller(file_path_IP, InputfilesListOoplane)
File "C:\ProjectMAPG\TRYPYTHON\src\OldPythonTry.py", line 67, in call_Controller
with open(InputfilesListOoplane) as f1:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
function to extract the file name:
def extractFilename(FileNameOnly):
stripText = string.split(FileNameOnly, " ")
FileName = stripText[0]
return (FileName)
pass
I think the problem is here. As the outplane have doesn't allow me to take in multiple folder:
def call_Controller(file_path_Inplane, InputfilesListOoplane):
FileNameOnlyIP = splitext(basename(file_path_Inplane))[0]
Name = extractFilename(FileNameOnlyIP)
#Extract raw inplane
with open(file_path_Inplane) as f:
f.readline()
#Extract raw outplane
with open(InputfilesListOoplane) as f1:
f1.readline()
return Name
Start of the program:
if __name__ == '__main__': #start of program
win = Tk.Tk() #Open up connection and declare button and label
master=win
initial_dir = "C:\VSM"
#Create Directory if its not there
try:
if not os.path.exists(newDirRH[0]):os.makedirs(newDirRH)
except: pass
#Open to select multiple files for files
file_path_Inplane= tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select VSM Files", multiple =1)
if file_path_Inplane != "": pass
else:
print "You didn't open anything!"
InputfilesListInplane = win.tk.splitlist(file_path_Inplane)
#Open to select multiple files for outplane
file_path_Ooplane = tkFileDialog.askopenfilename(initialdir=initial_dir, title="Select Out of Plane Files", multiple = 1)
if file_path_Ooplane != "":
pass
else:
print "You didn't open anything!"
InputfilesListOoplane = file_path_Ooplane#master.tk.splitlist(file_path_Ooplane)
for file_path_IP in InputfilesListInplane:
Name = call_Controller(file_path_IP, InputfilesListOoplane)
print "Done " + Name
I'm not sure what "in multiple outplane data" might be but the error message explains quite clearly:
'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
is not a valid file name. For me, this looks like two file names that you appended with a space between them.
When you open files, neither Python nor the OS will try to read your mind. Use a single file name per operation.
Prolem here:
IOError: [Errno 22] invalid mode ('r') or filename: u'C:/Users/zhenhui/Desktop/bye1.txt C:/Users/zhenhui/Desktop/hello1.txt'
Check correct place of delivery your path.
Next potential pronlem here initial_dir = "C:\VSM". Must initial_dir = "C:\\VSM" or initial_dir = "C:/VSM". Furthermore use path-related functions from os.path module.