No such file or directory found, Python [duplicate] - python

This question already has answers here:
Open file in a relative location in Python
(14 answers)
Closed 7 months ago.
I'm new to coding so I followed a tutorial for a chatbot, I need to import my intentions (which I named intentii, in my language) intentii.json into the chatbot, so I'm using:
intentii = json.loads(open('intentii.json').read())
I have seen other questions about the error I said in the title, and yes, I made sure the name is typed right, it's in the same exact directory as all my files including this chatbot one are, and still, it says it can't find the file, I tried placing the whole directory path and it seemed to work ( I didn't get the same error again, but an unicode error which I believe is another problem related to my .json file ), but I cannot use the whole path because I have to send this to my teacher and, of course, he won't have the same exact path as mine.
What is the solution?
Edit: Also, I've noticed that it says that for every file I need to access from the folder

Try this function to load a json file:
import json
def load_json(filepath):
with open(filepath) as f:
data = json.load(f)
return data
Then
intentii = load_json("intentii.json")

Try using this python os module to find dir_root where current file is located and then combine it json file name if it is stored in same directory.
import json
import os
dir_root = os.path.dirname(os.path.abspath(__file__))
intentii1 = json.loads(open(dir_root+'\js.json').read())

Related

How do you generalize a filepath in tkinter? [duplicate]

This question already has answers here:
How to find the real user home directory using python?
(9 answers)
Closed 1 year ago.
I finished up my first GUI project that allows the user to open any PDF file by wither typing a product key, or manually find it using a tree view. I have all the files in the same folder as the application, the problem is that when I used pyinstaller to make it an .exe it wont pull up. and anytime I move it nothing pulls up because the code is linked to that specific location. my question is how do you write it to where the filepath is linked to a specific folder, and even if said folder moves, it still accesses those files?
def Product_Look_UP():
if inPro.get()== "24LPPS":
Label(root, text= f"Searching for {inPro.get()}..." , fg = "Orange").grid(row = 3 , column = 0)
import webbrowser as wb
wb.open_new(r'C:\Users\user\Desktop\Product Finder\Data\Vender\vender\Ladder Pulls\24 in\Polished Stainless\LADDER PULL.pdf')
Essentially how do make "C:\Users\user\Desktop" be where ever the "Product Finder" folder is, whether it be on my computer, the server, or another persons computer?
You can call the function os.path.abspath and pass it the file name of your main python script and it will return the path where the file is. You can do something like this:
import os
import webbrowser as wb
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
wb.open_new(f"{CURRENT_DIR}/data/test.pdf")

Can't figure out where this error is coming from [duplicate]

This question already has an answer here:
Can't Open files from a directory in python [duplicate]
(1 answer)
Closed 1 year ago.
I'm working on a sentiment analysis program for an NLP class. I've imported a folder with a lot of different files and my goal is to merge all of the files text together to analyze it as one big pool of text. So far I've been able to import all of the files using:
path = "noblespeeches"
nobel_speeches = os.listdir(path)
files = sorted([file for file in nobel_speeches if file.endswith('.txt')])
...where "nobelspeeches" is the path to the appropriate file on my computer. I've tested this part and it seems to work fine. I'm having trouble creating a function to read the files so I can merge all of the text together.
def read_file(file_name):
with open(file_name, 'r+', encoding='utf-8') as file:
file_text = file.read()
return file_text
This function is what I've been working with, and I cannot seem to get it to work for the life of me. I'm sure the answer is quite simple, but I'm fairly new to Python and very new to NLP. I've been researching different possible solutions to no avail.
The error code is: FileNotFoundError: [Errno 2] No such file or directory:
The machine is producing an error that states that the first file in my folder doesn't exist even though it will acknowledge the file in the earlier code.
Chang this
files = sorted([os.path.join(path, file) for file in nobel_speeches if file.endswith('.txt')])

Problems Importing a .json file in PyCharm [duplicate]

This question already has answers here:
How do I read a json file into python?
(2 answers)
Closed 1 year ago.
I have a main.py file and an OrientationData.json file in a PyCharm project. I would like to import my data into main.py, but for some reason it will not allow me to. I have json imported in main.py, and both files are in the same venv folder of the project. If I try to import a .py file into main.py, I have no issues, but it simply does not recognize the json file when I try to import it.
(.py imports working just fine)
(.json import not working)
I have tried writing it as import OrientationData.json, but that also does not work. The specific error it's giving me is "no module named OrientationData" when I hover over the import statement. Why is this happening, and what can I do so that I can import and use my json data?
I don't think that is the proper way to read a .json file in python. If you are trying to read the .json file for your code, try this:
f = open('OrientationData.json', 'r')
data = json.load(f)
God bless
Try this:
Import json
file=open('data.json',r)
data=json.load(file.read)
#remember to close your file at the end
#or use a with block

How to create directory in ram and get path to it? [duplicate]

This question already has answers here:
How can I create a ramdisk in Python?
(4 answers)
Closed 3 years ago.
I'm looking for a library that allows to create a "fake" directory in RAM and get path to it that would work like a path to normal directory on disk.
My scenario is that I have a python script that executes another program (third party that I cannot modify) but it produces files and writes them to a specified location.
Then, in my script, I read these files and do something with them.
It's slow and I know that the bottleneck here is reading/writing files to/from disk (even if it's SSD).
Is it possible that I don't change the core of my script and only replace the temporary folder path that I use to store intermediate files?
I don't need them and I remove them after they are processed.
The perfect solution would be something like this:
import fakeRAM
tmp_dir_path = fakeRAM.get_path()
...
os.system("program.exe " + tmp_dir_path)
import tempfile
import pandas as pd
import io
data=pd.read_csv("data.csv")
temp = tempfile.NamedTemporaryFile(prefix="", suffix=".csv", mode='w+b', delete=False)
data.to_csv(temp.name)
print("The created file is", temp.name)

Python check if a directory exists, then create it if necessary and save graph to new directory? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 5 years ago.
so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs'):
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
I get the error :
AttributeError: 'module' object has no attribute 'mkdirs'
I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion.
os.mkdirs() is not a method in os module.
if you are making only one direcory then use os.mkdir() and if there are multiple directories try using os.makedirs()
Check Documentation
You are looking for either:
os.mkdir
Or os.makedirs
https://docs.python.org/2/library/os.html
os.makedirs makes all the directories, so if I type in shell (and get nothing):
$ ls
$ python
>>> import os
>>> os.listdir(os.getcwd())
[]
>>> os.makedirs('alex/is/making/a/path')
>>> os.listdir(os.getcwd())
['alex']
It has made all the directories and subdirectories. os.mkdir would throw me an error, because there is no "alex/is/making/a" directory.

Categories