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'}
Related
I have a class that looks like that:
class StoryManager:
STORIES = {1:'stories/itsmyluck.txt', 2:'stories/triptothezoo.txt', 3:'stories/loveatfirstsight.txt'}
def get_fields(self, directory):
self.pattern = re.compile(r'<\s*(.*?)\s*>')
self.results = []
with open(directory, 'r', encoding='utf-8') as f:
text = f.read()
self.matches = self.pattern.finditer(text)
for self.match in self.matches:
self.results.append(self.match[1])
return self.results
and another file that I write tests in:
from app import StoryManager
import unittest
class TestStoryManager(unittest.TestCase):
def test_get_fields(self):
result = ['case1','case2','case3','case4','case5','case6',
'case7','case8','case9','case10','case11','case12']
dirs = ['tests/story1.txt', 'tests/story2.txt', 'tests/story3.txt']
self.assertEqual(StoryManager.get_fields(dirs[0]), result)
if __name__ == '__main__':
unittest.main()
and the problem is that python says :
Traceback (most recent call last):
File "d:\Programowanie ;3\GitRepository\madlibs\test_storymanager.py", line 12, in test_get_fields
self.assertEqual(StoryManager.get_fields(dirs[0]), result)
TypeError: get_fields() missing 1 required positional argument: 'directory'
but as I can see there is argument(that is dirs[0]).
I feel like it is something simple but I can't find out what's wrong.
Thanks.
So, I have class that I use in a Flask app. I use this class in multiple pages, which is why I would like to save the creates class object in a pickle, and unpack it when I need it again. It just keeps on giving me errors.. I have a class that looks similar to this:
class files(name):
def __init__(self, name):
self.name = name
self.settings = Settings()
self.files_directory = self.settings.files_directory
self.files = self.create_list()
def store_files_from_folder(self):
loaded_files = []
files = list_files()
for file in files:
file_path = os.path.join(self.files_directory, file)
print('Loading file: {}'.format(file))
loaded_file = function_reads_in_files_from_folder(file_path, self.name)
loaded_files.append(loaded_file)
print('Loaded {} files'.format(len(loaded_files)))
and I'm trying to create the jsonpickle like this:
creates_class = files("Mario")
jsonpickle_test = jsonpickle.encode(creates_class, unpicklable=False)
result = jsonpickle.decode(jsonpickle_test, files)
But I get the following error:
Traceback (most recent call last):
File "C:\Users\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-23e9b5d176ac>", line 1, in <module>
result = jsonpickle.decode(jsonpickle_test, files)
File "C:\Users\lib\site-packages\jsonpickle\unpickler.py", line 41, in decode
data = backend.decode(string)
AttributeError: type object 'files' has no attribute 'decode'
And I can't get to resolve it. Could someone help me?
The problem is in the passed argument unpickable=False
unpicklable – If set to False then the output will not contain the information necessary to turn the JSON data back into Python objects, but a simpler JSON stream is produced.
You can avoid unpickable=False or load the produced data with json.loads to a dict and then use de kwargs arguments for the object creation
creates_class = files("Mario")
jsonpickle_test = jsonpickle.encode(creates_class, unpicklable=False)
result_dict = json.loads(jsonpickle_test)
create_class = files(**result_dict)
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)
My goal is to serialize a dictionary object to a specific file location, and read it back each time the program is run. The following works in Python2.7, but throws an error in Python3.4. What confuses me is that this works the first time an object is saved to disk, but not on subsequent executions.
The problem seems to be that in setitem an error is thrown that says that 'ConfigDict' object has no attribute '_config_file'. Why does it not have a value any time except the first time I run the script??
import os
import pickle
class ConfigDict(dict):
def __init__(self, config_name): # Name of a pickle file within configs directory
self._config_directory = 'C:\\Users\\myfilepath\\configs'
self._config_file = self._config_directory + '\\' + config_name + '.pickle'
# If file does not exist, write a blank pickle file.
if not os.path.isfile(self._config_file):
with open(self._config_file, 'wb') as fh:
pickle.dump({}, fh)
# Read the pickle file from disk.
with open(self._config_file, 'rb') as fh:
pkl = pickle.load(fh)
self.update(pkl)
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
with open(self._config_file, 'wb') as fh:
pickle.dump(self, fh)
cc = ConfigDict('DBConfig')
print()
print()
cc['config_val_1'] = '1'
cc['config_val_3'] = '3'
print(cc['config_val_3'])
Here's the full traceback:
Traceback (most recent call last):
File "C:/Users/filepath/test.py", line 25, in <module>
cc = ConfigDict('DBConfig')
File "C:/Users/filepath/test.py", line 16, in __init__
pkl = pickle.load(fh)
File "C:/Users/filepath/test.py", line 21, in __setitem__
with open(self._config_file, 'wb') as fh:
AttributeError: 'ConfigDict' object has no attribute '_config_file'
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()