How to find specific string while using lists? - python

I was making my simple filereader using python and cpython. But, I realized that it displayed an error that is TypeError: 'list' object has to attribute to find. Is there any way to find a specific character inside a list and return it? Thanks :D
Main python module
import io;
class AdvancedReader(object):
def __init__(self, file, mode=None, buffering=None, encoding=None, *args):
data_file = io.open(file, mode=mode, buffering=buffering, encoding=encoding)
striped_list = [lines.strip() for lines in (data_file.readlines())]
if any(map('['.startswith and ']'.endswith, striped_list)):
_starter = ([for item in striped_list.startswith('[')])
# stater = striped_list.filter('[', ‘]’) #Removing brackets
Simple using for class
AdvancedReader('settings.def', mode='r', buffering=-1, encoding='utf-8')
This is the atributte error that displayed inside my class...
Traceback (most recent call last):
File "main. py"
, line 13, in «module>
AdvancedReader("settinas.def".mode='r', buffering=-1. encoding='utf-g)
File "main.py", line 9, in
init
print(striped list. find(r))
AttributeError: list' object has no attribute 'find'
This is the settings.def file, its practically a new type of storage/file systax for python only.
[SYSTEM] // Begining acronym
start: os.system('echo hello world')
[/SYSTEM] // Ending acronym

Related

TypeError: 'StreamReader' object is not subscriptable while slicing the headers from file

I am facing this error when running the below code
from io import StringIO
class Runner(object):
#staticmethod
def runner(file_object):
data = file_object.readlines()
bdy = data[2:]
for line in bdy:
yield line
Error Log:
bdy = data[2:]
TypeError: 'StreamReader' object is not subscriptable
The error seems to be in bdy where it is not able to slice the data list that is obtained from file_object.readlines
Need to Fix this.
I guess you are trying to istanciate the class object in another part of the code and in that part you are calling the method runner but before make sure you opened the file correctly in read mode.
file = open("*your filename*", "r")
Finally you can call the method
my_runner = Runner()
my_runner.runner(file)
also it's good practice to close the file too
file.close()
If the problem persists check the length of the file, its existance in the folder and its path.

Opening a JSON file converting to dictionary in a class

I am opening and reading in a json file called, say, my_file.json located at ..\config\my_file.json in a python file called run_test.py. Ultimately, I would like to turn the JSON object into a python dictionary and do other stuff with it in python. I am running the below code from my terminal to execute the class:
python -c "from run_test import Update; x = Update('my_file.json'); print(x.why())"
This returns:
Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: why() missing 1 required positional argument: 'file_details'
I can't figure out why I'm getting this error. When I run (with return f in the body of read_file):
python -c "from run_test import Update; x = Update('my_file.json'); print(x.read_file())
This prints the dictionary I need. However, I would like to pass it to why so I can do other stuff with that dictionary. Yet, when I pass f to why, I get the above error. Why?
Here is the class I'm using:
import json
class Update:
def __init__(self, config_file_name):
self.config_file_name = config_file_name
def why(self, file_details):
return file_details
def read_file(self):
f = json.load(open('..\config\\' + self.config_file_name))
self.why(f)

Problems with pickle python

I recently made a program using an external document with pickle. But when it tries to load the file with pickle, I got this error (the file is already existing but it also fails when the file in't existing):
python3.6 check-graph_amazon.py
a
b
g
URL to follow www.amazon.com
Product to follow Pool_table
h
i
[' www.amazon.com', ' Pool_table', []]
p
Traceback (most recent call last):
File "check-graph_amazon.py", line 17, in <module>
tab_simple = pickle.load(doc_simple)
io.UnsupportedOperation: read
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "check-graph_amazon.py", line 42, in <module>
pickle.dump(tab_simple, 'simple_data.dat')
TypeError: file must have a 'write' attribute
Here is the code :
import pickle5 as pickle
#import os
try:
print("a")
with open('simple_data.dat', 'rb') as doc_simple:
print("b")
tab_simple = pickle.load(doc_simple)
print("c")
print(tab_simple)
print("d")
URL = tab_simple[0]
produit_nom = tab_simple[1]
tous_jours = tab_simple[2]
print("f")
except :
print("g")
URL = str(input("URL to follow"))
produit_nom = str(input("Product to follow"))
with open('simple_data.dat', 'wb+') as doc_simple:
print("h")
#os.system('chmod +x simple_data.dat')
tab_simple = []
tab_simple.append(URL)
tab_simple.append(produit_nom)
tab_simple.append([])
print(tab_simple)
print("c'est le 2")
print("p")
pickle.dump(tab_simple, 'simple_data.dat')
print("q")
The prints are here to show which lines are executed. The os.system is here to allow writing on the file but the error is persisting.
I don't understand why it's said that the document doesn't have a write attribute because I opened it in writing mode. And I neither understand the first error where it can't load the file.
If it can help you the goal of this script is to initialise the program, with a try. It tries to open the document in reading mode in the try part and then set variables. If the document doesn't exist (because the program is lauched for the first time) it goes in the except part and create the document, before writing informations on it.
I hope you will have any clue, including changing the architecture of the code if you have a better way to make an initialisation for the 1st time the program is launched.
Thanks you in advance and sorry if the code isn't well formated, I'm a beginner with this website.
Quote from the docs for pickle.dump:
pickle.dumps(obj, protocol=None, *, fix_imports=True)
Write a pickled representation of obj to the open file object file. ...
...
The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.
So, you should pass to this function a file object, not a file name, like this:
with open("simple_data.dat", "wb"): as File:
pickle.dump(tab_simple, File)
Yeah, in your case the file has already been opened, so you should write to doc_simple.

attributeerror 'module' object has no attribute 'openfile'

I'm trying to figure out the error that occurred using Python. I'm trying to use the module detektspikes.py freely distributed by klustakwik team.
I'm having trouble with errors that occurred when run.
Error log:
Exiting directory C:\Users\user\Downloads\klusta-team-spikedetekt-82bcf06\klusta
-team-spikedetekt-82bcf06\scripts_1
Traceback (most recent call last):
File "C:\Users\user\Downloads\klusta-team-spikedetekt-82bcf06\klusta-team-spik
edetekt-82bcf06\scripts\detektspikes.py", line 82, in <module>
spike_detection_job(raw_data_files, probe_file, output_dir, output_name)
File "C:\Python27\lib\site-packages\spikedetekt\core.py", line 86, in
spike_de
tection_job
probe, max_spikes)
File "C:\Python27\lib\site-packages\spikedetekt\core.py", line 115, in
spike_d
etection_from_raw_data
h5s[n] = tables.openFile(filename, 'w')
AttributeError: 'module' object has no attribute 'openFile'
I guess the problem is on the core.py
Core.py :
Filter, detect, extract from raw data.
"""
### Detect spikes. For each detected spike, send it to spike writer, which
### writes it to a spk file. List of times is small (memorywise) so we just
### store the list and write it later.
np.savetxt("dat_channels.txt", Channels_dat, fmt="%i")
# Create HDF5 files
h5s = {}
h5s_filenames = {}
for n in ['main', 'waves']:
filename = basename+'.'+n+'.h5'
h5s[n] = tables.openFile(filename, 'w')
h5s_filenames[n] = filename
for n in ['raw', 'high', 'low']:
if Parameters['RECORD_'+n.upper()]:
filename = basename+'.'+n+'.h5'
h5s[n] = tables.openFile(filename, 'w')
h5s_filenames[n] = filename
main_h5 = h5s['main']
# Shanks groups
shanks_group = {}
shank_group = {}
shank_table = {}
for k in ['main', 'waves']:
h5 = h5s[k]
shanks_group[k] = h5.createGroup('/', 'shanks')
for i in probe.shanks_set:
I would pleased to be kindly helped!
The problem is that that code is for a very old version of Python and trying to access a no longer existing method of tables. See here: http://www.pytables.org/MIGRATING_TO_3.x.html
If you want to run the script you'd have to run it in an old version of Python like 2.3, or update the lines that use openFile to use open_file instead. Though there may be other incompatibilities that I'm not aware of.

Python NoneType _getitem_ error

I'm working with a pice of software written in python from US CERT to do some fuzzing. Included in the software is a minimizer.py tool which is designed to be ran against certain test cases that cause crashes in order to determine exactly which byte mutations are causing the crash.
However when attempting to run the tool it's spitting an error at me. Google searches for both the tool and the error are drawing a blank. Attempting to troubleshoot it myself with limited python experience is not helping either. Any ideas on whats causing the error so I can fix it and get the tool working?
command line options being used are: minimizer.py --stringmode
The error output is as follows:
Traceback (most recent call last):
File "C:\FOE2\tools\minimize.py", line 234, in <module>
main()
File "C:\FOE2\tools\minimize.py", line 183, in main
config = Config(cfg_file).config
File "C:\FOE2\certfuzz\campaign\config\__init__.py", line 76, in __init__
self._set_derived_options()
File "C:\FOE2\certfuzz\campaign\config\foe_config.py", line 93, in _set_derived_options
t = Template(self.config['target']['cmdline_template'])
TypeError: 'NoneType' object has no attribute '__getitem__'
Segments of code from both of the files in last two lines of error are:
__init__.py:
def __init__(self, config_file):
self.file = config_file
self.config = None
self.load()
self._set_derived_options()
self.validations = []
self._add_validations()
self.validate()
def _set_derived_options(self):
pass
And then from foe_config_.py (added the preceding lines of code just in case they are relevant.):
class Config(ConfigBase):
def _add_validations(self):
self.validations.append(self._validate_debugger_timeout_exceeds_runner)
def _set_derived_options(self):
# interpolate program name
# add quotes around $SEEDFILE
t = Template(self.config['target']['cmdline_template'])
#self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=self.config['target']['program'])
self.config['target']['cmdline_template'] = t.safe_substitute(PROGRAM=quoted(self.config['target']['program']), SEEDFILE=quoted('$SEEDFILE'))
It's hard to tell from the code you posted, but it looks like __init__ sets self.config to None. Then it calls _set_derived_options which uses self.config here:
t = Template(self.config['target']['cmdline_template'])
But self.config hasn't changed from being None. You wouldn't expect None['target'] to give you anything (other than an Exception), but I think that is essentially what you're doing here.

Categories

Resources