My save code is written as so in a file called 'MachLearn.py':
Whilst looking for this code I find out I accidentally overwrote it with an old version :/. It was essentially structured like this:
class attibuteGenerator():
def __init__(self):
#more class stuff
def returnAttributes(self, rating, position):
#func stuff
if __name__ = "__main__":
ag = attributeGenerator():
with open('attributeGenerator_pickle', 'wb') as f:
pickle.dump(f, ag)
My open code is written as so in a file called "mainGame.py"
def main():
with open('attributeGenerator_pickle', 'rb') as f:
bob = pickle.load(f)
print(bob.returnAttributes(34, "LW"))
if __name__ == "__main__":
main()
Is there an issue with my code? It's giving:
This type of error arises when you attempt to unpickle an object, such as a class instance, and you don't have access to the relevant class in your current Python session. You should reimport the packages you were using to generate the objects that you pickled.
The following minimal script will reproduce this problem:
import pickle
class my_class():
def __init__(self):
self.x = 2
inst = my_class()
with open('file.dat', 'wb') as f:
pickle.dump(inst, f); f.close()
del my_class # Deletes the class and causes the problem
with open('file.dat', 'rb') as f:
new_inst = pickle.load(f); f.close()
with error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-6571eae10a31> in <module>
12
13 with open('file.dat', 'rb') as f:
---> 14 new_inst = pickle.load(f); f.close()
AttributeError: Can't get attribute 'my_class' on <module '__main__'>
This can be resolved by removing the line: del my_class.
Related
I am trying to read my dictionary(in my file) using ast
import ast
import os
class just_a_class():
def __init__(self, file,):
self.file = file()
self.read_file = open(self.file,'r+')
def read_file(self):
dict = ast.literal_eval(self.read_file.read())
return 'Input: \n\n {}'.format(dict)
the_class = just_a_class("dict.txt")
print(the_class.self.read_file())
Error:
Traceback (most recent call last):
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 13, in <module>
the_class = just_a_class("dict.txt")
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 6, in __init__
self.file = file()
TypeError: 'str' object is not callable
The code below is similar to what is used in the question. I've tried
to improve the readability by using common techniques and conventions,
such as using fname for the filename, instead of file, using a
context manager to open (and auto-close) the file, and capitalization
for class names. Also changed the flags to the open() call to be "r"
instead of "r+", as suggested by ShadowRanger.
import ast
class Just_a_class():
def __init__(self, fname):
self.fname = fname
def read_file(self):
with open(self.fname, 'r') as f:
dict = ast.literal_eval(f.read())
return 'Input: \n\n {}'.format(dict)
the_class = Just_a_class("dict.txt")
print(the_class.read_file())
# {'a': 5, 'b': 'hello'}
I'm trying to organize my code I already have by implementing classes and execute methods on classes instantiations. I have put some hours into figuring out how to use classes, but still haven't figured it out. Could someone help me?
This is the original code:
def readSignalAcquisitionData(fileName):
f = open(fileName, 'r')
# dummy read
f.readline()
timeStamps = []
dataInput = []
for ln in f:
# parse info
timeStr, dataStr = ln.split(',')
timeStamps.append(float(timeStr))
dataInput.append(float(dataStr))
f.close()
return timeStamps, dataInput
And this is what I currently have:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
def readSignalAcquisitionData(self):
f = open(self.fileName, 'r')
self.timeStamps = []
self.dataInput = []
for ln in f:
# parse info
self.timeStr, self.dataStr = ln.split(',')
self.timeStamps.append(float(self.timeStr))
self.dataInput.append(float(self.dataStr))
f.close()
return self.timeStamps, self.dataInput
def writeFilteredData(self, fileName, timeStamps, dataOut):
pass
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
print(timeStamps)
When I try running it through the terminal I get these error messages:
Traceback (most recent call last):
File "SignalDataEvaluationUnit_OOP.py", line 26, in <module>
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
File "SignalDataEvaluationUnit_OOP.py", line 7, in readSignalAcquisitionData
f = open(self.fileName, 'r')
AttributeError: 'str' object has no attribute 'fileName'
As #deceze♦ says in comment, you haven't instantiated the class SignalDataIOUnit, that's why it doesn't work.
To make it work, you have 2 choices:
Instantiating SignalDataIOUnit object and call the method readSignalAcquisitionData:
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
Use Python's #staticmethod decorator:
class SignalDataIOUnit:
def __init__(self, fileName):
self.fileName = fileName
#staticmethod
def readSignalAcquisitionData(fileName):
...
then just call it as usual
timeStamps, dataInput = SignalDataIOUnit.readSignalAcquisitionData(fileName)
yes, you should use like this
fileName="LabsWeek03_inputData.csv"
timeStamps, dataInput = SignalDataIOUnit(fileName).readSignalAcquisitionData()
print(timeStamps)
I'm trying to make a config file manager that stores dictionaries in a pickle file, in a config folder in the same directory. I'm having issues with a pesky AttributeError that claims I don't have an attribute '_name', which I defined in the first line of init().
The main program has 2 classes, one inheriting from Exceptions (the error class) and the other inheriting from dict (the main class). The init takes a name and finds if the file exists. If it doesn't, then an empty dictionary is written to the given file.
I receive the error when I:
1. open an existing file to print the keys
2. write a key and value pair to an existing file
3. try and get a key from the dictionary
I've tried not calling dict.setitem in init and nothing changed, I still get the error. I tried just loading the file while doing absolutely nothing else to it, and couldn't get it to work.
import os
import pickle
class ConfigDict(dict):
'''
This class is responsible for all main functions.
Pass a string as an argument without a file type.
Keywords such as 'database' and 'aiconstructer' work well.
'''
def __init__(self, name):
self._name = name+'.pickle'
if not os.path.isfile(self._name):
with open(self._name, 'wb') as f:
pickle.dump('{}', f)
with open(self._name,'rb') as f:
obj = pickle.load(f)
if len(obj) > 2:
for k in obj.keys():
dict.__setitem__(self, k, obj[k])
def __getitem__(self, key):
if not key in self.keys():
raise ConfigKeyError(self, key)
return dict.__getitem__(key)
def __setitem__(self, key, val):
dict.__setitem__(self, key, val)
with open(self._name, 'wb') as f:
pickle.dump(self, f)
The Traceback is as follows:
Traceback (most recent call last):
File "interface.py", line 12, in <module>
test = ConfigDict('alpha')
File "/home/bear/Desktop/Config/confdict.py", line 35, in __init__
obj = pickle.load(f)
File "/home/bear/Desktop/Config/confdict.py", line 47, in __setitem__
with open(self._name, 'wb') as f:
AttributeError: 'ConfigDict' object has no attribute '_name'
The code for interface.py that initiates this is:
import sys
from confdict import ConfigDict, ConfigKeyError
test = ConfigDict('alpha')
if len(sys.argv) == 3:
key = sys.argv[1]
val = sys.argv[2]
print('Writing')
test[key] = val
print('Done')
elif len(sys.argv) == 2:
key = sys.argv[1]
print('{}:{}'.format(key,test[key]))
else:
print('Keys : Values')
print('-----------------')
for k in test.keys():
print('{} : {}'.format(k,test[k]))
I expect to be able to load the contents of the pickle file into self, but instead I get the AttributeError. Is it something I'm doing grammatically wrong, or is there a rule that I forgot to follow? Thank you very much for any help in advance.
So this is my code, I would like to save the value 'test' to the file so that it can be called to be used when the program is reopened.
import pickle
test = 0
def Save():
with open('objs.pickle', 'wb') as f:
pickle.dump(test, f)
def Load():
with open('objs.pickle', 'rb') as f:
test = pickle.load(f)
The problem with this code is that when I reopen the program and run in and then type in Load(), it says that 'test' is still equal to 0. (Missing somehting obvious probably)
And so my question is, how could I fix the problem issued in italics?
The global variable test has nothing to do with test inside the function Load(). Change your function to:
def Load():
with open('objs.pickle', 'rb') as f:
return pickle.load(f)
Now this function returns the value it reads from the pickle file.
Call it like this:
print(Load())
Side note: By convention functions names are all lowercase in Python. So the function name should be actually load().
EDIT
The whole program in a better style:
import pickle
def save(file_name, obj):
with open(file_name, 'wb') as fobj:
pickle.dump(obj, fobj)
def load(file_name):
with open(file_name, 'rb') as fobj:
return pickle.load(fobj)
def main():
test = 0
file_name = 'objs.pickle'
save(file_name, test)
print(load(file_name))
if __name__ == '__main__':
main()
I'm new to Python and currently learning, I had a task to do some reading and writing to files with a python script. The reading part of my script seems to work as expected however the write section is throwing an error. It's probably something trivial I have done but here is my code:
class LogMessage():
def __init__(self, filename):
self.filename = filename
def read(self):
inputFile = open(self.filename)
for line in inputFile:
print(line, end='')
def write(self):
outputFile = open(self.filename)
#writeInput = input('What data do you wish to write?:\n')
for line in writeInput:
print(line,file = outputFile, end='')
filename = LogMessage('new.txt')
filename.read()
writeInput = input('What data do you wish to write?:\n')
LogMessage.write(writeInput)
The read part works but taking user data and writing it to the file and gives this error:
Traceback (most recent call last):
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 22, in <module>
LogMessage.write(writeInput)
File "/home/alex/workspace/Python/Learn Python/labEx9.py", line 11, in write
outputFile = open(self.filename)
AttributeError: 'str' object has no attribute 'filename'
can anyone help me, thanks a lot.
Alex
You must call 'write' on 'filename', which is an instance of LogMessage, not on the LogMessage class.
Apart from this, there are other issues (e.g. 'writeInput' is not defined in method 'write')
If you get such errors while using flask check your html code( your_form.) and add this to your html :
<form method="POST" action="" enctype="multipart/form-data">
enctype="multipart/form-data" would help.
class LogMessage():
def __init__(self, filename):
self.filename = filename
def read(self):
inputFile = open(self.filename)
for line in inputFile:
print(line, end='')
def write(self):
writeInput = input('What data do you wish to write?:\n')
outputFile = open(self.filename, 'w')
for line in writeInput:
print(line, file = outputFile, end='')
filename = LogMessage('new.txt')
filename.write()
filename.read()