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)...
I want to know how can I fix this program so it can work properly....can someone...
I want to know how can I fix this program so it can work properly....can someone run it and give me the fixed version but do not the entire program bear with this one please and thanks in advance!!!!! import java.util.Scanner; public class ifPractice { public static void main(String[] args) { Scanner KB = new Scanner(System.in); { double option; double option02; double stu_gradeTest01; double stu_gradeTest02; double stu_gradeTest03; double final_grade; { System.out.println("Enter #1 to see what test to grade first, #2...
How can I fix this code to accomplish the goal of reading and writing on binary...
How can I fix this code to accomplish the goal of reading and writing on binary or text files? 3 import java.io.*; 4 import java.io.FileOutputStream; 5 import java.io.FileInputStream; 6 import java.util.Scanner; 7 8 public class ReadAndWrite implements Serializable 9 { 10 public static void main(String[] args) 11 { 12 boolean file = true; 13 Scanner inputStream; 14 PrintWriter outputStream; 15 FileInputStream inputBinary; 16 FileOutputStream readBinary; 17 FileInputStreamText writeText; 18 FIleOutputStreamText readText; 19 StringBuffer contents = new StringBuffer(); 20 Scanner keyboard...
In python I have my code written and I want just 4 functions to be fix...
In python I have my code written and I want just 4 functions to be fix in my code according to rule. My code is running but it has some problem regarding to rules. (I have did all the other things so you do not have to worry about other functions) 1) all the players has to play until he/she reaches to at least 500 points in first round. When user reach 500 points for the first time, user may...
I keep getting the error below in zbooks. How can I fix this. Thank You JAVA...
I keep getting the error below in zbooks. How can I fix this. Thank You JAVA zyLabsUnitTest.java:14: error: cannot find symbol s = MidtermProblems.difference(75, 75); ^ symbol: method difference(int,int) location: class MidtermProblems 1 error import java.lang.Math; public class MidtermProblems { public static String difference(int a, int b) { int diff = Math.abs(a - b); String ans = "";    if (diff == 0) { ans = "EQUAL";    } else if (diff > 10) { ans = "Big Difference "...
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...
I need to make 2 possible suggestions on how Comcast can fix the problem with their...
I need to make 2 possible suggestions on how Comcast can fix the problem with their customer service, and how Comcast can possibly improve the whole business overall while briefly discussing the impacts of these suggestions. Please put in a paragraph with the heading above, I Must come up with 350 words in total.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT