Attempting to modify CSV value based on the input received - python

Below is an example of the code, essentially I am taking input received and attempting to modify an existing CSV value. The problem is the code runs and produces the "print" output as expected, but the values are not being modified to "True" or "False" based on the if and else statements:
def test():
sn_cmn = pd.read_csv('cmn_location.csv')
wan = re.findall(r'Tunnel12', str(router_output)) or re.findall(r'Tunnel13', str(router_output))
hostname = re.search(r'...-....-R.', str(router_output))
hostname_string = str(hostname)
site_code = hostname_string[-13:-10]
if wan == ['Tunnel12'] or wan == ['Tunnel13']:
answer = 'Yes'
if answer == 'Yes':
for site in sn_cmn.u_site_code:
sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'TRUE'
else:
for site in sn_cmn.u_site_code:
sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'FALSE'
sn_cmn.to_csv('new_cmn_location.csv')

Related

Python IF statements not running despite conditions met

In my code I have grabbed an integer from a text file and globally declared it as the variable 'accessLevel1', so it could be used to run validation checks in other areas of the code. However, despite the variable value being saved as '2' when using the first staff login details, an IF statement dependent on the variable being '2' is not running at all.
The contents of the text file titled 'staffDetails':
Jonas,Hills,JHills375,Sweirl900,2,
Ellie,Glover,EGlover919,KHaisen10,1,
Code used for grabbing the variable:
validateStaff = open("staffDetails.txt", "r")
for row in validateStaff:\
record = row.split(",")
if record[2] == (entered_text):
forename = record[0]
surname = record[1]
username = record[2]
password = record[3]
accessLevel = record[4]
if record[3] == (entered_text2):
global forename1
global accessLevel1
global surname1
surname1 = surname
forename1 = forename
accessLevel1 = accessLevel
The problem code
def modclick(): #A function that occurs when a button is pressed
print("Your access level is: " + (accessLevel1)) #This is here for demonstrative purposes of the problem
if accessLevel1 == '1':
errorLabelstock.config(fg='red') #this actually works somehow
if accessLevel1 == '2':
modifystock() #This function isn't called despite printing that the access level is 2
if accessLevel1 == '3':
modifystock()
Proof that the system interpretted the variable 'accessLevel1' to be of the value 2 yet not executing the IF statement:
Try adding the following line, this will fix it
accessLevel1 = str(accessLevel1).strip()

Pandas passing dataframe as a parameter , but variables are not getting proper values inside the function

numbers_1 = zero['_Mobile'].tolist()
def getmessage(number,df1):
#get the points, gender and name...
message = 'Hello! Greetings from Royale Touche'
try:
name = df1.loc[df1['_Mobile'] == number,'Name'].tolist()[0]
points = df1.loc[df1['_Mobile'] == number, 'Total_Credit_Points'].tolist()[0]
gender = df1.loc[df1['_Mobile'] == number, 'Gender'].tolist()[0]
print(gender)
if gender.lower() == 'male':
title = 'sir'
else:
title = 'mam'
return message
except:
print("not found",number)
message = getmessage(numbers_1[I],zero)
Problem here is Gender is coming as Male for every iteration in the loop.. and its not changing to female. is there any bug in pandas?
You most likely getting the same result because you hard coded I at the top of your code, so your always inputting the same variable
That being said here is a suggested update for your getmessage function
def getmessage(number, df1):
name, points, gender = df1.loc[df1['_Mobile'] == number][['name', 'points',
'gender']].iloc[0].tolist()
title = 'sir' if gender.lower() == 'male' else 'mam'

Editing a list of dictionaries from a list created from a txt file

I am trying to exclude and remove some dictionaries from a list. I have searched for awhile through the site and haven't found anything specific to this. The list of dictionaries was created from a txt file located: http://s000.tinyupload.com/?file_id=48953557772434487729
I'm trying to sort out and exclude the things I don't need. I thought my syntax was right, but apparently not.
I only included necessary code to cut down on the clutter. I am having problems at the action_genre point and excluding and deleting the dictionaries there. When prompted enter "s" and then "a" to access those two menus.
def load_movies():
global movies_list
movies_list= []
file_ref = open("movies.txt", 'r')
line = file_ref.readline()
for line in file_ref:
line = line.strip()
current = {}
if line == '':
break
movie_data = line.split("\t")
current["title"] = movie_data[0]
current["year"] = movie_data[1]
current["length"] = movie_data[2]
current["rating"] = movie_data[3]
current["action"] = int(movie_data[4][0]) == 1
current["animation"] = int(movie_data[4][1]) == 1
current["comedy"] = int(movie_data[4][2]) == 1
current["drama"] = int(movie_data[4][3]) == 1
current["documentary"] = int(movie_data[4][4]) == 1
current["romance"] = int(movie_data[4][5]) == 1
movies_list.append(current)
del current
file_ref.close()
def menu():
movie_selector =("Movie Selector - Please enter an option below:\nL - List all movies\nY - List all movies by year\n"
"T - Search by title\nS - Search by genre, rating, and maximum length\nQ - Quit the program\nOption:")
movie_selector_input = input(movie_selector).upper()
if movie_selector_input == "L":
list_movies()
if movie_selector_input == "Y":
list_by_year()
if movie_selector_input == "T":
search_by_title()
if movie_selector_input == "S":
search()
if movie_selector_input == "Q":
print("Thanks for using my program! Goodbye.")
exit()
else:
print("Invalid input")
print("Please try again")
print()
return menu()
def search():
genre_input = input("Please make a selection from the following genres.\n(Action(A), Animation(N), Comedy(C), "
"Drama(D), Documentary(O), or Romance(R)):").lower()
if genre_input == 'a':
action_genre()
elif genre_input == 'n':
animation_genre()
elif genre_input == 'c':
comedy_genre()
elif genre_input == 'd:':
drama_genre()
elif genre_input == 'o':
documentary_genre()
elif genre_input == 'r':
romance_genre()
else:
print("Invalid genre")
print()
menu()
#this is where I can't get the syntax to work
def action_genre():
for current in movies_list:
if current["action"] == "False":
del current
break
for i in movies_list:#using this to test output
print(i)
load_movies()
menu()
I'm narrowing down the list by excluding things that don't fit the parameters. In the action_genre function, I'm trying to delete all the dictionaries that don't equal current["action"] == True. I've tried using "True" and "False" as strings, as well as the bools True and False for comparisons, and still an error. Unfortunately, I have to use the Boolean logic per my professors directions.
His e.g.:
Professor's example. Apparently since I'm new I can't embed images. :/
I'm in programming 101, so thank you for your patience as I learn this, and thank you in advance for the help.
Okay, so the issue runs a bit deeper than the if condition being incorrect. In get_action() you effictively do not modify the actual movies_list object, but rather the local variable current, as proven by this simple test:
def action_genre():
for current in movies_list:
print(current)
if not current["action"]:
del current
print(current)
The second print(current) will result in an UnboundLocalError saying that current does not exist anymore, while in movies_list the entry it just deleted continues to exist. But in general, using del in loops indeed causes problems because that's how iterables and del itself behave. I encourage you to read up more on this on other sources or SO if you wish, like here.
Using the answer from the provided link above, we can use list comprehension to filter the movies:
def action_genre():
filtered_movies_list = [movie for movie in movies_list if movie['action']]
print(filtered_movies_list)
This creates a new list (so it does not modify movies_list), which includes all dictionary entries where item['action'] == True.
I hope this helps.
You are trying to compare a string with a boolean. Look at the following:
a= 1==1
print a
True
print type(a)
<class 'bool'> # a is a boolean
b='True' #assign string 'True' to b
print type(b)
<class 'str'>
print a==b #compare boolean True to string 'True'
False
b = True # assign boolean True to b
print a==b #compare boolean True to boolean True
True
so you need if current["action"] == False instead of if current["action"] == "False"

How to access python objects with a dynamic object name?

I have a question to one of my python scripts. I'm using the library untangle (https://github.com/stchris/untangle) to import and convert xml config files into the main script.
The problem: I have user informations in the config file for more than one user and I'm using this information in a loop. It works very well, but it makes the script very ugly due to the name of the generated objects from the xml file.
Concrete this means I can't (or I just don't know how) change the name of the object I would like to use dynamic.
The example code is below:
if employee == 0:
if str(configobj.config.modes.employee.employee_1.name.cdata) != '':
display.drawtext(0,0,str(configobj.config.modes.employee.employee_1.name.cdata),"7x13B",255,255,255,True)
if str(configobj.config.modes.employee.employee_1.line1.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_1.line1['x']),
int(configobj.config.modes.employee.employee_1.line1['y']),
if str(configobj.config.modes.employee.employee_1.line2.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_1.line2['x']),
int(configobj.config.modes.employee.employee_1.line2['y']),
if str(configobj.config.modes.employee.employee_1.line3.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_1.line3['x']),
int(configobj.config.modes.employee.employee_1.line3['y']))
displayimage = True
elif employee == 1:
if str(configobj.config.modes.employee.employee_2.name.cdata) != '':
display.drawtext(0,0,str(configobj.config.modes.employee.employee_2.name.cdata),"7x13B",255,255,255,True)
if str(configobj.config.modes.employee.employee_2.line1.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_2.line1['x']),
int(configobj.config.modes.employee.employee_2.line1['y']),
if str(configobj.config.modes.employee.employee_2.line2.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_2.line2['x']),
int(configobj.config.modes.employee.employee_2.line2['y']),
if str(configobj.config.modes.employee.employee_2.line3.cdata) != '':
display.drawtext(int(configobj.config.modes.employee.employee_2.line3['x']),
int(configobj.config.modes.employee.employee_2.line3['y']),
if str(configobj.config.modes.employee.employee_2.image.cdata) != '':
display.showimage(160,0,str(configobj.config.modes.employee.employee_2.image.cdata))
displayimage = True
And this is a lot of repeated code with a changing number. How can I improve this?
Use getattr:
getattr(configobj.config.modes.employee, 'employee_' + str(employee + 1)).name.cdata
You can also create separate variable for employee:
employee = getattr(configobj.config.modes.employee, 'employee_' + str(employee + 1))
print(employee.name.cdata)
print(employee.line1['x'])

Print lists in a dictionary based on the status of change/depchanges

Following is what I am trying, not sure where I'm messing up. I have the expected output at the bottom. Can anyone provide input on what is wrong here?
Create a lists in a dictionary for each master change and its dependent change
Repeat step #1 until the depchange status is not NEW
My code:
def depchange(change):
depchange_status=''
if change == "23456":
depchange=33456
depchange_status == 'NEW'
if change == "33456":
depchange=""
depchange_status == 'COMPLETED'
return (depchange,depchange_status)
def main ():
master_change="23456"
dep={}
while True:
dep_change,depchange_status=depchange(master_change)
master_change = dep_change
dep[master_change]=dep_change
if depchange_status != 'NEW':
break
print dep
if __name__ == '__main__':
main()
'''
EXPECTED OUTPUT:-
dep = {
'23456': ['33456'],
'33456': [],
}
'''
Uh, in your depchange() function, do you actually mean to compare the depchange_status, or do you mean to change them? You had '==' there.
There's that, and in that same function, depchange is switched from a string to an int. I assume you wanted it to stay a string.
def depchange(change):
depchange_status=''
if change == "23456":
depchange="33456"
depchange_status = 'NEW'
if change == "33456":
depchange=""
depchange_status = 'COMPLETED'
return (depchange,depchange_status)
def main ():
master_change="23456"
dep={}
while True:
dep_change,depchange_status=depchange(master_change)
dep[master_change]=[dep_change]
master_change = dep_change
if depchange_status != 'NEW':
break
print dep
if __name__ == '__main__':
main()
Swap the order of these two lines. You want to use the old value of master_change in the assignment to dep.
master_change = dep_change
dep[master_change]=dep_change
Also you have == instead of = in a couple of assignments.
depchange_status == 'NEW'
depchange_status == 'COMPLETED'

Categories

Resources