AttributeError: 'module' object has no attribute 'urlopen' (Python 2.7) - python

I am writing a program for my school, and I'm hosting the daily SBWATs (Students Will Be Able To) for each teacher in text files. Here is my code, SchoolNet.py
import Tkinter
import urllib
print urllib.__file__
def showsbwat(teacher):
sbwat = urllib.openurl("192.168.1.203/" + teacher + ".txt")
print sbwat
def showshecdule():
mainwindow.withdraw()
schedulewindow.deiconify()
firstperiodbutton = Tkinter.Button(schedulewindow, text = periodlist[0], command = lambda: showsbwat(periodlist[0]))
firstperiodbutton.pack()
global sbwatlabel
sbwatlabel = Tkinter.Label(schedulewindow, text = "")
sbwatlabel.pack()
def login():
try:
schedulefile = open(usernamevar.get() + ".txt", "r")
global periodlist
periodlist = schedulefile.readlines()
print periodlist
mainwindow.deiconify()
loginwindow.withdraw()
except:
usernamevar.set("Invalid ID")
loginwindow = Tkinter.Tk()
loginwindow.wm_title('Login to SchoolNet')
mainwindow = Tkinter.Tk()
mainwindow.wm_title('SchoolNet')
schedulewindow = Tkinter.Tk()
schedulewindow.wm_title('SchoolNet Schedule')
mainwindow.withdraw()
schedulewindow.withdraw()
loginwindow.deiconify()
schedulebut = Tkinter.Button(mainwindow, text = 'Schedule', command=showshecdule)
schedulebut.pack()
usernamevar = Tkinter.StringVar()
usernameentry = Tkinter.Entry(loginwindow, textvariable=usernamevar)
usernameentry.pack()
loginbut = Tkinter.Button(loginwindow, text="Login", command=login)
loginbut.pack()
Tkinter.mainloop()
But, when I run it, I keep getting this error:
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "SchoolNet.py", line 12, in <lambda>
firstperiodbutton = Tkinter.Button(schedulewindow, text = periodlist[0], com
mand = lambda: showsbwat(periodlist[0]))
File "SchoolNet.py", line 6, in showsbwat
sbwat = urllib.openurl("192.168.1.203/" + teacher + ".txt")
AttributeError: 'module' object has no attribute 'openurl'
I have tried this with urllib and urllib2, but I get the same error. None of the other files in the directory are named the same of any python modules. What am I doing wrong?
I'm using Python 2.7

It is urlopen not openurl:
urllib.urlopen()

from urllib.request import urlopen
URL = "www.webpage-address"
page= urlopen(URL)
text = page.read()

Related

Python OSError 22 in parsing XML file that exists and has valid filename

I'm attempting to parse one or more XML files that are exported from the Bricklink website. I'm opening the file via the defusedxml ElementTree system.
Every file I attempt to open gets me OSError 22 upon the opening attempt, even with what appears to be valid filenames - I can open the files with other tools and can see the contents.
The trace is:
Traceback (most recent call last):
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "D:/Jason/Projects/Projects/wantedlist_modder.py", line 48, in processfiles
tree = ET.parse(filename)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\site-packages\defusedxml\common.py", line 105, in parse
return _parse(source, parser)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\xml\etree\ElementTree.py", line 1202, in parse
tree.parse(source, parser)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python38\lib\xml\etree\ElementTree.py", line 584, in parse
source = open(source, "rb")
OSError: [Errno 22] Invalid argument: "'D:/Jason/Downloads/LF_LtN_2020.xml'"
The python code is as follows:
from tkinter import messagebox, filedialog
import tkinter as tk
from defusedxml.ElementTree import *
import defusedxml.ElementTree as ET
import io
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.pack(padx = 20, pady = 20)
frame = Frame(self)
frame.pack(side = TOP)
# create variable for input field
self.filename = tk.StringVar()
self.filename.set("")
# create input field
self.inputfile = tk.Entry(frame)
self.inputfile.pack(side = LEFT)
self.inputfile["textvariable"] = self.filename
# create browse button
self.browse = tk.Button(frame, text = "Browse...", command = self.openbrowse)
self.browse.pack(side = LEFT)
# create process button
self.process = tk.Button(self, text = "Process", command = self.processfiles)
self.process.pack(side = TOP, padx = 20, pady = 20)
# create quit button
self.quit = tk.Button(self, text = "QUIT", fg = "red", command = self.master.destroy)
self.quit.pack(side = BOTTOM)
def openbrowse(self):
filenames = tk.filedialog.askopenfilenames(title = 'select', filetypes = [("XML", ".xml"),])
if not filenames is None:
self.filename.set(', '.join(repr(u) for u in filenames))
def processfiles(self):
print("Roger, roger!")
filenames = tuple(self.filename.get().split(','))
showdone = 0
for filename in filenames:
try:
print(filename)
tree = ET.parse(filename)
showdone = 1
except FileNotFoundError:
tk.messagebox.showinfo("Wanted List Modder", "Please enter a valid filename")
if showdone:
tk.messagebox.showinfo("Wanted List Modder", "Done!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
I've done a lot of hunting to try to fix this but none of the fix candidates I've found on this site or elsewhere seem to change what's going on (e.g. I'm parsing from file not string). I'm not sure the contents are an issue, this seems to be something related to the filename - or the way I'm passing it to the parse function. It does print the name of the file it's processing, and I'm using the Browse button system to locate the file. I know that leads to some extra processing converting to/from tuple, but I don't think that's the culprit because the variable value passed to parse is a string.
Running Python 3.8.6 with defusedxml 0.6.0 on a Windows 7-x64 machine... and would really like assistance determining the cause of the OSError please.
Thanks in advance - and apologies if it's something simple! I haven't used Python in a while and I'm battling the adverse neurological effects of chemo...
See below - you have extra " in the file name
# your code with a bug
try:
with open('"c:/temp/a.xml"', 'rb') as f:
pass
except OSError:
print('we have a problem')
# bug was removed - it works
with open('c:/temp/a.xml', 'rb') as f:
print('it works')

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!

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

Python Tkinter Error (Weather API)

I have this program which uses a Weather API and gets the weather of a city.
The city is read from a text file.
Here's the Python File:
import urllib2
import json
from string import capitalize
import Tkinter as tk
city = ''
data = open('data.txt', 'r+')
for i in data:
if 'current_city' in i:
index = len(i)
city = i[13:index]
print city
def kelvinToCelsius(kelvin_temp):
return str(int(kelvin_temp)-273) + ' Degree Celsius'
def setText(string, string_var):
string_var.set(string)
def getCurrentTemperature(city):
city = city.replace(' ', '%20')
url_to_call = 'http://api.openweathermap.org/data/2.5/weather?q=' + city
response = urllib2.urlopen(url_to_call)
json_obj = json.load(response)
print url_to_call
current_desc = capitalize(json_obj['weather'][0]['description'])
current_temp = kelvinToCelsius(json_obj['main']['temp'])
setText(city, city_name_label_text_var)
return current_desc + ': ' + current_temp
maingui = tk.Tk()
city_temp_and_desc_label_text_var = tk.StringVar()
city_name_label_text_var = tk.StringVar()
main_frame = tk.Frame(maingui, width=500, height=200, borderwidth=2)
main_frame.pack()
city_name_label = tk.Label(main_frame, textvariable=city_name_label_text_var, font=12).place(x=226, y=0)
city_temp_and_desc_label = tk.Label(main_frame, textvariable=city_temp_and_desc_label_text_var, font=30).place(x=140, y=99)
setText(getCurrentTemperature(city), city_temp_and_desc_label_text_var)
tk.mainloop()
Please help! I learned from the error that the problem is that the city name is not read from the text file properly and is equal to '' when it is passed to the url.
I tried many different ways to avoid this error but none of them worked.
EDIT: I forgot to mention but an initial program writes the text to the text file and then runs the above python script. I also forgot to mention this but when the above file is run directly, it works. But when I checked the rerouting python script writes properly to the text file.
Here's the error:
Traceback (most recent call last):
File "D:\Anand\Coding\Eclipse IDE\eclipse\WorkBench\The Weather\src\__main__.py", line 54, in <module>
setText(getCurrentTemperature(city), city_temp_and_desc_label_text_var)
File "D:\Anand\Coding\Eclipse IDE\eclipse\WorkBench\The Weather\src\__main__.py", line 35, in getCurrentTemperature
current_desc = capitalize(json_obj['weather'][0]['description'])
KeyError: 'weather'

loading from a .txt file, no file directory

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

Categories