Question

In: Computer Science

In Python: how can I fix the IsADirectoryError: [Errno 21] Is a directory: ??? this is...

In Python: how can I fix the IsADirectoryError: [Errno 21] Is a directory: ???

this is my code:

#importing sqlite and pandas

import sqlite3

import pandas as pd



#goal

print("Welcome! The goal of this assigment is to create a database to find meanings and synonyms for given phrases.")

#Connecting database

conn = sqlite3.connect("keilavaldez.db")

#Creating cursor to remove existing specified tables

cur = conn.cursor()

#creating tables

cur.execute("CREATE TABLE Synsets([SynsetID] INTEGER,[Definition] text)")

cur.execute("CREATE TABLE Phrases([SynsetID] INTEGER,[phrase] text)")

conn.commit()

#opening and reading table named "synsets"

with open("//Users//keilavaldez//Desktop//assigment 10", 'r') as f:

for line in f:

data = line.split('\t')

cur.execute('INSERT INTO synsets (SynsetID, Definition) VALUES (?, ?)', (data[0], data[1].strip()))

#opening and reading table named "phrases"

with open("//Users//keilavaldez//Desktop//assigment 10", 'r') as f:

for line in f:

data = line.split('\t')

cur.execute('INSERT INTO phrases (SynsetID, phrase) VALUES (?, ?)', (data[0], data[1].strip()))


#Asking the user to enter a phrase

#checking if the phrase its in the database

#checking phrases even if they are lower

phrase = str(input("Please enter a phrase: "))

query = 'SELECT * FROM phrases WHERE phrase=' + "'"+ phrase.lower() + "'"

df = pd.read_sql_query(query, conn)

#if phrase is not in database, asking the user to try again

if df.empty:

print("Phrase/word not found. Please try again!")

#returning output if output is in database

#printing how many meanings the phrase has

#printing synonyms, printing unique synonyms

#prinit

else:

result_query = 'SELECT DISTINCT s.SynsetID,Definition FROM phrases p INNER JOIN synsets s ON s.SynsetID=p.SynsetID WHERE phrase=' + "'"+ word.lower() + "'"

result_df = pd.read_sql_query(result_query, conn)

lst = result_df['SynsetID'].values.tolist()

query = 'SELECT DISTINCT phrase,SynsetID FROM phrases WHERE SynsetID IN (SELECT DISTINCT s.SynsetID FROM phrases p INNER JOIN synsets s ON s.SynsetID=p.SynsetID WHERE phrase=' + "'"+ word.lower() + "') AND phrase<>"+ "'"+ word.lower() + "'"

df = pd.read_sql_query(query, conn)

syn = df['phrase'].values.tolist()

print("There are "+ str(len(lst)) +" meanings and "+ str(len(syn)) +" unique synonyms")

j=1

#priniting along with the synset ID

#printing all synonyms

for i in lst:

print("The meaning of this word: ",j)

print(result_df[result_df['SynsetID']==i]["The definition of this word: "].values[0])

print("Synset ID: ")

print(i)

print("Synonyms:")

words = df[df['SynsetID']==i]['phrase'].values.tolist()

for w in words:

if w!=phrase.lower():

print(w)

j=j+1

Solutions

Expert Solution

Hello! :)

You are getting this error because:

//Users//keilavaldez//Desktop//assigment 10

is a directory (a folder) and not a file.

I hope this example can make it clearer for you to understand:

prog.py:

def function(location):
    try:
        with open(location) as f:
            for line in f:
                print(line)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    function('file')
    function('directory')

Here is the snapshot of a demo run:

The function runs successfully without any exceptions when the location leads to a file but it throws the exception you mentioned when the location leads to a directory.

So, you can overcome the exception by replacing these lines like this:

- with open("//Users//keilavaldez//Desktop//assigment 10", 'r') as f:
+ with open("<insert-valid-file-location-here>", 'r') as f:

Hope this helps! :)


Related Solutions

Python: How would I write a function that takes a directory and a size in bytes,...
Python: How would I write a function that takes a directory and a size in bytes, and returns a list of files in the directory or below that are larger than the size. For example, I can use this function to look for files larger than 1 Meg below my Home directory.
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) #...
Python 3 Fix the code so i can make the window larger and the fields increase...
Python 3 Fix the code so i can make the window larger and the fields increase size Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window)...
Python 3 What to fix: When i click the clear button it clears everything but not...
Python 3 What to fix: When i click the clear button it clears everything but not the sold by field import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money...
Why my net pay is always 0, and how can I fix it ? here's the...
Why my net pay is always 0, and how can I fix it ? here's the code #include <iostream> #include <fstream> #include <iomanip> #include <cmath> using namespace std; int main() { ofstream out; out.open("myData.txt"); string fname;    cout << "name?" << endl; cin >> fname; double salary; cout << "salary?" << endl; cin >> salary;    double fedTax = salary * 15 / 100; double stateTax = salary* 3.5 / 100; double SST = salary * 5.75 / 100; double...
In python can you fix the error in the line where it says message = input("Input...
In python can you fix the error in the line where it says message = input("Input a lowercase sentence: ") this is the error message I get after running the program and inputing a lowercase sentence Input a lowercase sentence:hello hi MM§MTraceback (most recent call last): MM§M File "client.py", line 14, in <module> MM§M message = input("Input a lowercase sentence:") MM§M File "<string>", line 1 MM§M hello hi MM§M ^ MM§MSyntaxError: unexpected EOF while parsing from socket import * #...
Python 3 Fix code everytime i hit submit all the fields in the fomr should be...
Python 3 Fix code everytime i hit submit all the fields in the fomr should be cleaned # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs") #window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=3, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) # arraging barcode.grid(row=0, column=1) product.grid(row=1,...
Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
Hello I have this error in the code, I do not know how to fix it....
Hello I have this error in the code, I do not know how to fix it. It is written in C++ using a Eclipse IDE Error: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string bus.h =========== #pragma once #include using namespace std; class Bus { private:    string BusId; // bus ID    string Manufacturer; // manufacturer of the bus    int BusCapacity; // bus capacity    int Mileage; // mileage of bus    char Status; // current status...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT