How to disable selected lines by the char "#" in one time? - python

Whatever is the code, i'm just searching for the way to disable some lines directly in one time by char "#".
For example, i have this code :
import json
def get(user):
try:
with open("tokens.json") as f:
data_token = json.load(f)
f.close()
return str(data_token["tokens"][user])
except:
return False
def check(user, token_key):
with open("tokens.json", 'r') as f:
data_tokens = json.load(f)
f.close()
for ids, tokens in data_tokens["tokens"].items():
if str(ids) == str(user):
if int(tokens) == int(token_key):
if __name__ == '__main__':
print(get("User1"))
And i temporary want to disable my fonction named "check()" because it makes a error right now :
import json
def get(user):
try:
with open("tokens.json") as f:
data_token = json.load(f)
f.close()
return str(data_token["tokens"][user])
except:
return False
#def check(user, token_key):
# with open("tokens.json", 'r') as f:
# data_tokens = json.load(f)
# f.close()
# for ids, tokens in data_tokens["tokens"].items():
# if str(ids) == str(user):
# if int(tokens) == int(token_key):
if __name__ == '__main__':
print(get("User1"))
I already seen some guys doing that and i wanted to know how to do.
Thanks ;)

Related

Delete comments with python function

Anybody can advise what could be wrong with my code?
I am trying to make a method that removes the single line comments from the content.
Also, the method should return the single line comments that start with '#'.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
def deleteComment(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comment= 0
if i[0] == "#":
comment += 1
else:
pass
with open("clean-", "w") as f:
f.write(clean)
f.close()
my_file.close()
except:
print("An error occurred with accessing the files")
return file
This should make it work.
import os
def deleteComments(file):
try:
my_file = open(file, 'r')
data = my_file.read()
clean = ""
comments_count = 0
for i in data.split('\n'):
if i[0] == "#":
clean += i
clean += '\n'
comments_count += 1
else:
pass
name = os.path.basename(path)
with open("clean-" + name, "w") as f:
f.write(clean)
f.close()
my_file.close()
return comments_count
except:
print("An error occurred with accessing the files")
return file

Error while using click module in python - Error: No such option: --addtask

Error - Error: No such option: --addtask
I ran code using - python3 main.py --addtask task
On running this addtask function should execute but it isnt
Saw several youtube videos still couldnt fix it
Pls help!
code below
Code -
import click
import json
from rich.console import Console
console = Console()
filename = './db.json'
#click.group()
def cli():
pass
def veiw_data():
with open(filename,'r') as f:
temp = json.load(f)
for entry in temp:
print(entry)
def get_data(name:str):
with open(filename, 'r') as f:
temp = json.load(f)
for entry in temp:
if entry['name'] == name:
return entry
def insert_data(data:dict):
with open (filename, 'r') as f:
temp = json.loads(f)
print(temp)
temp.append(data)
with open(filename, 'w') as f:
json.dump(temp,f,indent = 4)
def delete_data(name:str):
with open(filename, 'r') as f:
temp = json.loads(f)
i = 0
for entry in temp:
if entry[name] == name:
temp.pop(i)
i+=1
#click.command()
#click.option('--addtask',help='Add a task')
def addtask(task):
data = {
"name":task
}
insert_data(data)
console.print(f'[bold cyan]Task Added -[/bold cyan] [red]{task}[/red]')
cli.add_command(addtask)
if __name__ == '__main__':
cli()
```
try this rename click with cli an remove the line : cli.add_command(addtask)
#cli.command()
#cli.option('--addtask',help='Add a task')
def addtask(task):
data = {
"name":task
}
insert_data(data)
console.print(f'[bold cyan]Task Added -[/bold cyan] [red]{task}[/red]')

Deleting data in pickle

I have a pickle db with 5 variable in it that goes : rafTur, rafKat, rafNo, rafIndex, rafIndexData. I'm trying to delete a data inside my pickle file. My main goal is taking an input from user that goes like this :
rafTur = S rafKat = 1 rafNo = 2 rafIndex = 3
And then finding that imput from my pickle file that named noSqlDB. and then delete the entire data about input.
def delPic():
infile = open('noSqlDB', 'rb+')
sistem = pickle.load(infile)
flag = False
rafTur = str(input('Rafın türünü giriniz : '))
rafKat = int(input('Rafın katını giriniz : '))
rafNo = int(input('Rafın Nosunu giriniz : '))
rafIndex = int(input('Rafın indexini giriniz : '))
# read to the end of file.
for x in range((len(sistem) + 1)):
try:
if (sistem['rafTur'].upper() == rafTur.upper() and sistem['rafKat'] == rafKat and sistem['rafNo'] == rafNo and sistem['rafIndex'] == rafIndex):
del sistem
flag = True
sistem = pickle.load(infile)
except EOFError:
break
if flag == False:
print('Record not Found')
infile.close()
When i run this code nothing changes. The data stays on noSqlDB. How can i delete the data inside the noSqlDB ? like this
I tried changing
del sistem
to
del sistem['rafTur'],sistem['rafKat'], sistem['rafNo'],sistem['rafIndex'],sistem['rafIndexData']
def unpickle_database(filename):
with open(filename, 'rb') as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
def save_object(obj, filename,a):
if a < 1:
with open(filename, 'wb+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
else :
with open(filename, 'ab+') as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
def delPic():
temp =0
students = list(unpickle_database('noSqlDB'))
for student in students:
print(student)
save_object(student, 'noSqlDB',temp)
temp += 1
Found a solution after trying some code here it is.

Combine two python with statements that share the same code

def test(file_name):
if file_name.lower().endswith('.gz'):
with gzip.open(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
if file_name.lower().endswith('.csv'):
with open(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
Question> Is there a better way to combine the above code without duplicating the 'Same Code' section? The function test uses gzip.open if the the file_name is a gz file otherwise it opens with regular open.
One way would be:
def test(file_name):
loader = None
if file_name.lower().endswith('.gz'):
loader = gzip.open
elif file_name.lower().endswith('.csv'):
loader = open
if loader is not None:
with loader(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
def test(file_name):
f = None
if file_name.lower().endswith('.gz'):
f = gzip.open(file_name)
if file_name.lower().endswith('.csv'):
f = open(file_name)
if f is not None:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
f.close()

Python 3: Why am I getting an AttributeError?

I'm running Python 3 and I'm getting the following error:
AttributeError: 'AssemblyParser' object has no attribute 'hasMoreCommands'
Here is the code that is raising the error:
import sys
from Parser import AssemblyParser
from Code import Code
parser = AssemblyParser(sys.argv[1])
translator = Code()
out_file = str(sys.argv[1]).split(".")
out_file = str(out_file[:1]) + ".hack"
with open(out_file, 'w', encoding='utf-8') as f:
while parser.hasMoreCommands():
parser.advance()
if parser.commandType() == "A_COMMAND":
dec_num = parser.symbol()
binary = "{0:b}".format(dec_num)
elif parser.commandType() == "C_COMMAND":
default_bits = "111"
comp_bits += translator.comp(parser.comp())
dest_bits += translator.dest(parser.dest())
jump_bits += translator.jump(parser.jump())
binary = default_bits + comp_bits + dest_bits + jump_bits
assert len(binary) == 16
f.write(binary)
Here is my Parser.py file:
class AssemblyParser:
"""
Encapsulates access to the input code. Reads an assembly language command,
parses it, and provides convenient access to the command's components (fields and symbols).
In addition, removes all whitespace and comments.
"""
def __init__(self, input_file):
self.current_command = ""
self.next_command = ""
with open(input_file,"r+", encoding='utf-8') as f:
for l in f:
line = "".join(l.split()) # Remove whitespace from the line
line = line.split('//') # Removes any comments from the line
clean_line = line[0]
if clean_line.strip(): # Removes any blank lines
f.write(clean_line)
next_command = f.readline()
def __hasMoreCommands__(self):
if self.next_command:
return true
return false
def __advance__(self):
with open(input_file, encoding='utf-8') as f:
self.current_command = self.next_command
self.next_command = f.readline()
def __commandType__(self):
char_1 = self.current_command[:1]
if char_1 == "#":
return "A_COMMAND"
elif char_1 == "(":
return "L_COMMAND"
else:
return "C_COMMAND"
def __symbol__(self):
assert self.commandType() == ("A_COMMAND" or "L_COMMAND")
if self.commandType() == "A_COMMAND":
symbol = str(symbol[1:])
else:
symbol = str(symbol[1:len(symbol)-1])
return str(symbol)
def __dest__(self):
assert self.commandType() == "C_COMMAND"
if "=" in self.current_command:
temp = self.current_command.split("=")
return str(temp[:1])
else:
return ""
def __comp__(self):
assert self.commandType() == "C_COMMAND"
temp = self.current_command
if "=" in temp:
temp = temp.split("=")
temp = str(temp[1:])
if ";" in temp:
temp = temp.split(";")
temp = str(temp[:1])
return temp
def __jump__(self):
assert self.commandType() == "C_COMMAND"
if ";" in self.current_command:
temp = self.current_command.split(";")
return str(temp[1:])
else:
return ""
I really don't know why I'm getting this error, I've looked at the import documentation, but I'm getting more and more confused. I'm fairly new to Python. Can anyone explain this error?
Thanks.
Well. There seems to be no function in Parser module with name hasMoreCommand. The function in there starts with underscore and end eith underscore.
Two leading and trailing underscores are used to identify "magic" attributes. You can't use that to create your own, as they only reference pre-existing methods.
The following is what you probably want:
hasMoreCommands():
If you have multiple classes with this function, use name mangling instead:
_hasMoreCommands():
See: https://stackoverflow.com/a/8689983/2030480
And: http://www.rafekettler.com/magicmethods.html

Categories

Resources