importing specific class not working - python

i've created a file with the name enviroment.py which contain a Profile class however when i in another file try to import the file like import testProject.enviroment import Profile i get below error
yaml_helper.py", line 11, in read_yaml
with open(file_path, 'r') as f:
IOError: [Errno 2] No such file or directory:
however i'm not sure why it gives this error since the Profile hasnt even been initialized. all i've done is imported it?
enviroment.py
class Profile(object):
def __init__(self, profile):
self.profile = yaml_helper.read_yaml(project.default_profiles_dir, profile)
self.run_enviroment()
def get(self, key):
return self.profile.get(key)
def run_enviroment(self):
return common.validate(connectors.exasol_credentials, self.profile)

That's not an import error. That's an error when the program is trying to open a file. The problem is where you call yaml_helper.read_yaml.
Are you passing in the correct parameters? for example, in that call, you are passing in project.default_profies_dir What is project? I don't see it defined. That could be your problem.

Related

Unpickling a class raises attribute error

I wrote a class A in the Class_A.py file
class A():
def square(self, num):
return num*num
Next in pickle_A.py, I saved the class in a file 'class_A_imported_from_class_A'
import pickle
from Class_A import A
if __name__ == '__main__':
file_name = 'class_A_imported_from_class_A'
with open(file_name,'wb') as f:
pickle.dump(A,f,pickle.HIGHEST_PROTOCOL)
Then I moved the file to another location, where I ran Unpickling_imported_class.py to unpickle this file.
import pickle
file_name = 'class_A_imported_from_class_A'
with open(file_name,'rb') as f:
B = pickle.load(f)
So, I get the error:
B = pickle.load(f)
builtins.ModuleNotFoundError: No module named 'Class_A'
Now, I know that the error will go, if I copied the Class_A into this folder. The constraint is that I cannot.
I was able to do this using cloudpickle, but in that, I have to pickle the file also using cloudpickle.
My work demands that I should be able to unpickle classes directly, i.e. if there's a pickled file that has the data for a class, I should be able to read a class directly. Is there a way that I can do it?

Creating Python submodule

I want to create a tool called unifile for saving and opening files
like this unifile.open.yaml("file.yaml").
This is my structure:
unifile
|
├-open
| └--__init__.py
|
└-save
└--__init__.py
Code that call my module:
import unifile
a = unifile.open.yaml("file.yaml")
open/init.py
import yaml
class open():
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
1 error if I import unifile always say:
module unifile has no atribute open
2 error in __init__.py I can't open file
[pylint] Context manager 'open' doesn't implement enter and exit. [not-context-manager]
here adding solution to ur problem, make your project structure like this.
add unifile/__init__.py file in the unifile itself not in other modules.
then unifile/open/_open.py file content
import yaml
class Open():
def __init__(self):
pass
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
content of the unifile/__init__.py file
from .open._open import Open
in terminal run the program like this
Also, It is better to create a object element first then proceed ahead.
Two issues, two answers.
First, you should add an init file in unifile. With this, Python will understand that unifile is a package with a sub package.
Second, open is a built-in function and you overwrite it by calling your class open. Change your class name and it should work.
You are getting this error because unifile is not a package. There isn't any init.py file at the top level same as open and save. You also cannot call open.yml directly, because open is a class in package open, so either you will have to import open from open, create its instance and then call iml on that instance.
from open import open
a = open().yml('file.yml')
You are getting this error, because you are trying to override an existing keyword in Python open which you should strictly prohibit doing. So you should name your class anything except a reserved keyword.

Xlsxwriter cant find file for close() in Django Project

I am attempting to write a class to create an excel sheet using my Django Models. I have created the following class:
class workBook(object):
def __init__(self, title, data):
path = '\\workbooks\\' + title + '.xlsx'
print(os.path.normpath(path))
self.workbook = xlsxwriter.Workbook(os.path.normpath(path))
newWorkSheet(self.workbook, data)
self.workbook.close()
The method creates the workbook with the proper path but when I close it I get the following error:
[Errno 2] No such file or directory: '\\workbooks\\Test.xlsx'
I know this is because of the double "\" but I dont know how to send the correct path to the close method. I also know the rest of my class works because it does not throw this error when I simply put the file name and not a full directory.
Thank you!
I fixed it by just using "/" instead of "\" in a custom path.

Define a class to write into a file in Python

In this code I tried to define a class which will write into a file.In the init method the name of the file is passed.I also defined a method named "write" to write to the file.Then I created an instance of the class and passed the value of the file name.After that, I called the write method and passed the message to write in the file.At last, I checked if the file is created and if the file has the message.Here's the code:
class Logfile(object):
def __init__(self,file_name):
self.file_name = file_name
def write(self,msg):
with open('self.file_name','w') as myFile:
myFile.write(msg)
log = Logfile('myNewFile.txt')
log.write("this is a log file.")
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
But, it shows an error:
FileNotFoundError: [Errno 2] No such file or directory: 'myNewFile.txt'
This python code is saved in a desktop folder called "My Folder".And when I go there, there is really no such file named "myNewFile.txt".
But, if I run the program with the checking part of the code, I mean,this part:
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
then, there is no error but still the "myNewFile.txt" is not created.
Can you please help me?
In the write method you should write :
with open(self.file_name, ‘w’) as my_file
because self.file_name is already a string.
log = Logfile('myNewFile.txt')
log.write("this is a log file.")
with open('myNewFile.txt','r') as readFile:
read_file = readFile.read()
for line in read_file:
print(line)
You could always try to open the file using with open(log) because you have already made the .txt file a variable. I have never tried this and have little experience with this type of code, but it could be worth a shot.

In Django, how do I get a file path for an uploaded file when uploading?

I am trying to add some validation for user uploaded files. This requires running through a custom script I made called "sumpin", which only takes a filepath as a variable and sends back JSON data that will verify. Everything inside my script is working independently, putting it together where the error occurs.
Since this is file validation, I decided to expand my file_extension validator that was already working.
models.py
from allauthdemo.fileuploadapp.slic3rcheck import sumpin
def user_directory_path_files(instance, filename):
return os.path.join('uploads', str(instance.objectid), filename)
def validate_file_extension(value):
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.stl','.STL']
if not ext in valid_extensions:
raise ValidationError(u'Please upload a .stl file type only')
data = sumpin(value.path)
print (data)
class subfiles(models.Model):
STL = models.FileField(_('STL Upload'),
upload_to=user_directory_path_files, validators=[validate_file_extension])
The error that I get is that the path (value.path) is not valid.
This is the incorrect path because the upload_to tag must change this at a later point. This may be obvious, but I also need to have the file at the filepath location when my script is called. So essentially my questions are...
How can pass the "upload_to" path into my validator to run through my custom script?
Is there a better method to deal with uploaded files, like in the main class with a "save" or "clean" function?
I've found my own answer, but I'll post it here in case someone runs across this issue in the future.
I was incorrect, a validator wouldn't actually download the file. I need to use a file upload handler, which is shown below.
import os
from django.core.files.storage import default_storage
from allauthdemo.fileuploadapp.slic3rcheck import sumpin
def handle_uploaded_file(f):
with open(default_storage.path('tmp/'+f.name), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
data = sumpin(default_storage.path('tmp/'+f.name))
os.remove(default_storage.path('tmp/'+f.name))
return data
then I call this inside my views.py.
from allauthdemo.fileuploadapp.uploadhandler import handle_uploaded_file
#login_required
def STLupload(request):
# Handle file upload
if request.method == 'POST':
formA = ObjectUp(request.POST, request.FILES)
if formA is_valid():
data = handle_uploaded_file(request.FILES['STL'])
This will return whatever I called to return within handle_upload_file, which worked perfect for my issues. Hopefully someone will find this useful the future.

Categories