loading from a .txt file, no file directory - python

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

Related

Automatically get the date created and rename the file to it

I was wondering if there was a way to automatically get the date created and rename the file to it. I was coding in it a bit, but then I got an error. The error said FileNotFoundError: [WinError 2] The system cannot find the file specified: 'AutoDateRename'. Where AutoDateRename is the name of the folder I want the renamed files to go into. Is there a way to do this?
The Full Error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\lucio\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "c:/Users/lucio/Documents/PythonWorkspace/FileAutoDateRename/script.py", line 21, in RenameDateCreated
os.rename(rf'{E1_Val.get()}/{filename}',rf'{E1_Val.get()}/AutoDateRename/{time.ctime(os.path.getctime(filename))}')
File "C:\Users\lucio\AppData\Local\Programs\Python\Python38-32\lib\genericpath.py", line 65, in getctime
return os.stat(filename).st_ctime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'AutoDateRename'
My Code:
from tkinter import *
from tkinter import filedialog
import os.path, time
import os
window = Tk()
window.title("File Auto Date Rename")
window.geometry("500x300")
window.resizable(width=False,height=False)
E1_Val = StringVar()
def SelectFolder():
window.filename = filedialog.askdirectory()
E1.delete(0,"end")
E1.insert(END,window.filename)
def RenameDateCreated():
os.mkdir(f'{E1_Val.get()}/AutoDateRename')
for filename in os.listdir(E1_Val.get()):
os.rename(rf'{E1_Val.get()}/{filename}',rf'{E1_Val.get()}/AutoDateRename/{time.ctime(os.path.getctime(filename))}')
L1 = Label(text="Auto Date Rename",font='Helvetica 16 bold underline')
L1.pack()
L2 = Label(text="Folder Path",font='Helvetica 12 bold italic')
L2.pack(pady=5)
E1 = Entry(window,textvariable=E1_Val)
E1.pack(pady=5)
B1 = Button(window,text="Locate",height=1,width=5,command=SelectFolder)
B1.pack(pady=5)
L4 = Label(text="Rename Options",font='Helvetica 12 bold italic')
L4.pack(pady=5)
B2 = Button(window,text="Rename Using Date Created",height=1,width=25,command=RenameDateCreated)
B2.pack(pady=2)
B3 = Button(window,text="Rename Using Date Modified",height=1,width=25)
B3.pack(pady=2)
L5 = Label(text="Make sure that the folder you\nare converting is backed up in a safe location!",font='Helvetica 14 bold')
L5.pack(pady=15)
window.mainloop()
Since you created a directory AutoDateRename inside the source directory (returned by E1_Val.get(), it will be included in the list returned by os.listdir() and I think you don't want to rename it. So you should check whether the source file is a file and not a directory.
And os.path.getctime(filename) should be os.path.getctime(os.path.join(E1_Val.get(), filename)) instead.
Also time.ctime() may return string with characters (like :) that are not allowed in filename. Use time.strftime() to format the time to be a valid filename.
Below is an updated RenameDateCreated():
def RenameDateCreated():
srcdir = E1_Val.get().strip()
if srcdir:
destdir = os.path.join(srcdir, 'AutoDateRename')
os.makedirs(destdir, exist_ok=True) # create the directory if it does not exists
for filename in os.listdir(srcdir):
srcpath = os.path.join(srcdir, filename)
if os.path.isfile(srcpath): # only process file, not directory
ctime = time.strftime('%Y%m%d_%H%M%S', time.localtime(os.path.getctime(srcpath)))
destpath = os.path.join(destdir, f'{ctime}_{filename}')
os.rename(srcpath, destpath)

Trying to return search results from a txt file to GUI

So I am trying to write some code that needs to search through a .txt file and return the results to a basic GUI I have created. Here is my code so far. When I click the "search" button in the GUI, nothing happens.
My code so far:
import re
from tkinter import *
def query():
search = lookfor.get()
datafile = open("data.txt", "r")
for line in datafile.readlines():
if re.query(search, line, re.I):
findings.insert(INSERT)
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings.pack()
root.mainloop()
I've also tried a different way of searching the txt file:
import re
from tkinter import *
def query():
datafile = open("data.txt", "r")
for line in datafile:
line = line.strip()
elements = line.split("\t")
if str(lookfor.get()) in elements[0]:
findings.insert(INSERT, elements[1])
elif str(lookfor.get()) in elements[1]:
findings.insert(INSERT, elements[0])
findings.insert(END, '\n')
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings .pack()
root.mainloop()
Upon running your program, (after fixing the query() issue), it produces an AttributeError:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/usr/Documents/main.py", line 9, in query
if re.query(search, line, re.I):
AttributeError: module 're' has no attribute 'query'
Instead of using re.query() (which doesn't exist), use re.search() (which takes the exact same parameters).
Also, there is a TypeError on line 10:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "/Users/usr/Documents/main.py", line 10, in query
findings.insert(INSERT)
TypeError: insert() missing 1 required positional argument: 'chars'
This is fixed by changing the line from:
findings.insert(INSERT)
To:
findings.insert(INSERT, line)
Putting this all together gives the following program:
import re
from tkinter import *
def query():
search = lookfor.get()
datafile = open("data.txt", "r")
for line in datafile.readlines():
if re.search(search, line, re.I):
findings.insert(INSERT, line)
datafile.close()
root = Tk()
lookfor = Entry(root)
lookfor.pack()
Button(root, text = "Search", command = query).pack()
findings = Text(root)
findings.pack()
root.mainloop()
Hope that helps!

Python 3.5 Tkinter how to save dict to file

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.

How can I use askopenfile to get a valid filename

I'm trying to create a program with Tkinter and tkFileDialog that opens a file for reading and then packs it into a text widget but, whenever I run this:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(str(file), "r+")
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
I get this:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:\Users\super\PycharmProjects\untitled1\File Picker.py", line in filefind
f = open(str(file), "r+")
IOError: [Errno 22] invalid mode ('r+') or filename: "<open file u'C:/Users/super/PycharmProjects/untitled1/util.h', mode 'r' at 0x00000000026E0390>"
Here is the issue; askopenfile() is returning an object, not just the name. If you print file, you will get <_io.TextIOWrapper name='/File/Path/To/File.txt' mode='r' encoding='UTF-8'>. You want the name= from the object. To get that, all you need to do is replace f = open(str(file), "r+") with f = open(file.name, "r+").
Here is how it will look in your code:
from Tkinter import *
from tkFileDialog import askopenfile
import time
m = Tk()
def filefind():
file = askopenfile()
f = open(file.name, "r+") # This will fix the issue.
x = f.read()
t = Text(m)
t.insert(INSERT, x)
t.pack()
b = Button(m, text='File Picker', command=filefind)
b.pack()
m.mainloop()
Edit
A cleaner way of doing this is by letting askopenfile() do the work of opening a file instead of 're-opening' it again with open(). Here is the cleaner version:
file = askopenfile()
x = file.read()

What's Wrong With My Code? (ValueError: I/O operation on closed file)

Can Someone Explain to me what is wrong with my code? I get the following error:
Traceback (most recent call last): File "C:\LineRep.py", line
15, in module:
for line in File2: ValueError: I/O operation on closed file
My Code:
import os, Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirprompt = tkFileDialog.askopenfilename()
File = open (dirprompt, 'r')
File2 = open (dirprompt + 'temp', 'w')
for line in File:
File2.write(line.replace(',', ' '))
File.close()
File2.close()
names = []
for line in File2:
names.append(line)
print names
You are iterating over File2 after you call File2.close()

Categories