Writing to text file error - python

Hi I am working on a program to store some files to a text document that can be reloaded when necessary. Below is the beginning of the code however when run I receive a trace back error stating "recipe_title is not defined" when I thought I had defined it as the name of the text file. Please help show me what I have done wrong.
import sys
opt=0
def choice1():
print("WORKED")
def choice2():
Recipe_Name = input("Please enter a recipe name: ")
Recipe_List = open(recipe_title.txt,"w")
Recipe_List.write(recipe_title+"\n")
def ingredient_input_loop(recipe_title, ):
Recipefile = open(recipe_title,"w")
if(ingredient== "end" or "End" or "END" or "EnD" or "eNd" or "enD" or "ENd" or "eND"):
Recipe.write(recipe_title)

recipe_title.txt is your file name and not a variable. Therefore you should add quotes
Recipe_List = open('recipe_title.txt',"w")
or if the recipe_title is really a variable:
Recipe_List = open('{}.txt'.format(recipe_title),"w") # now you can open brocolli.txt for example
General feedback about your code:
Variable names should not have Uppercase characters. This should only
be used for Class names.
Checking if for all the combinations of 'end' can be written to if ingredient.lower() == "end":

Related

Input from user to print out a certain instance variable in python

I have created a class with programs:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
Channel 1, start:16.00 end:17.45 viewers: 100 name: Matinee:The kiss on the cross
Channel 1, start:17.45 end:17.50 viewers: 45 name: The stock market today
Channel 2, start:16.45 end:17.50 viewers: 30 name: News
Channel 4, start:17.25 end:17.50 viewers: 10 name: Home building
Channel 5, start:15.45 end:16.50 viewers: 28 name: Reality
I also have created a nested list with the programs:
[[1,16:00, 17,45, 100, 'Matinee: The kiss on the cross'],[1,17:45, 17,50, 45,'The stock market today'],[2,16:45, 17,50, 30,'News'], [4,17:25, 17,50, 10,'Home building'],[5,15:45, 16,50, 28,'Reality']
Now we want the user to be able to write the name of a program:
News
The result should be:
News 19.45-17.50 has 30 viewers
I thought about how you could incorporate a method to avoid the program from crashing if the input is invalid/ not an instance variable
I have tried this:
Check_input():
print('Enter the name of the desired program:')
while True: #Continue asking for valid input.
try:
name = input('>')
if name == #is an instance?
return name
else:
print('Enter a program that is included in the schedule:') #input out of range
except ValueError:
print('Write a word!') #Word or letter as input
print('Try again')
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory"
Do you have any suggestions how to combat the problem?
All help is much appreciated!
I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)
Well if all your programs have a unique name then the easiest approach would probably be to store them in a dictionary instead of a nested list like:
programs = {
"News": Program("2", "16:45", "17:50", "News", "30", "60"),
"Reality": <Initialize Program class object for this program>,
...
}
Then you could just use the get dictionary method (it allows you to return a specific value if the key does not exist) to see if the asked program exists:
name = input('>')
program = programs.get(name, None)
if program:
print(program)
else:
# raise an exception or handle however you prefer
And if your programs don't have a unique name then you will have to iterate over the list. In which case I would probably return a list of all existing objects that have that name. A for loop would work just fine, but I would switch the nested list with a list of Program objects since you already have the class.
I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory" Do you have any suggestions how to combat the problem.
I would say that the most elegant solution is to override the __str__ method of your Program class so that you can just call print(program) and write out the right output. For example:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
def __str__(self):
return self.name + " " + self.start + "-" + self.end + " has " + self.viewers + " viewers"
should print out
News 19.45-17.50 has 30 viewers
when you call it like:
program = programs.get(name, None)
if program:
print(program)

How do I use an input to print a class definition?

I am trying to code something basic in python just for fun and I encountered an issue,
# Employee is a class with the initialization being self, name, status
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
print(e1.status)
# printing e1 status will make "Present" or "Absent"
while True:
try:
cmd = input("Cmd: ")
if cmd == "status_check":
who = input("Who: ")
# putting in e1 or e2 will get their respective statuses
I've tried everything I can think off like, making it so that it gets a number out of the input("Who: ") input so I can better use eval or exac, but doing that makes it so I cant run e1.status because all it has is a 1 and I can't make a "e" appear in front of it so I can't run e1.status. I've also tried using just eval or exac but that didn't get the wanted result because I would have to type my code in the input("Cmd: "). That's isn't the only things I've tried but those are some that come to mind.
I'm just stumped here.
If you want to map names to values, you don't want separate variables. You want a dictionary.
Rather than
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
Consider
employees = {
'e1': Employee("Tom, Lincoln", "Present"),
'e2': Employee("Sam, Bradley", "Absent"),
}
To access an employee, write
print(employees["e1"].status)
and then you can use the input string to subscript employees as well.
who = input("Who: ")
print(employees[who].status)
one other approach is to use sys module:
import sys
# class definitions etc
while True:
try:
cmd = input("Cmd: ")
if cmd == "status_check":
who = input("Who: ")
atr = getattr(sys.modules[__name__], who)
print(atr.status)

How to use variable from constructor inside of methode?

Hi guys hope u are doing well, i'm new with python :)
so i have two issues the first how can i use the variable name from the init to my function game() which it use two args (those args whose make it realy difficult for me !) as u can see in code bellow:
# FUNCTION.py
class penGame():
def __init__(self):
print("Welcome to Pendu Game")
self.name = input("Enter your name: ") # IMPORT THIS VARIABLE FROM HERE
def game(self, letter, rword):
letter = letter.lower()
if letter in rword:
for Id, Value in enumerate(rword):
if Value == letter:
donnee.default_liste[Id] = letter
else:
name2 = self.name # it deosn't work i got 1 missing arg when i run the code from MAIN.py
print(f"try again {name} it's wrong ")
print("-".join(donnee.default_liste))
The second issue is i need to use the same variable (name) from init in another module which is my main module and i couldn't use it cause i tried to create an object from class penGame() like:
myObject = penGame()
name2 = myObject.name
then use the name2 inside of the if condition as u can see bellow but it doesn't work properly cause it run the init again which is not what i want actualy !
any idea how can i did it plz?
#MAIN.py
import donnee
from fonctions import penGame
random_word = random.choice(donnee.liste_words) # creation of random word from liste_words
penGame() #call the constructor
while donnee.counter < donnee.score:
letter = input("Enter the letter: ")
if penGame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
penGame.game(letter, random_word) # as u can see that's the reason cause i supposed to send 3 args instead of two ! but i only need those two !!?
if penGame.check_liste():
myObject = penGame() # that's cause runing the init everytime !!
name2 = myObject.name
print(f"congratulation {name2} you've guessed the word, your score is: {donnee.choice-donnee.counter} point.")
break
if penGame.loser():
print(f"the word was {random_word.upper()} you have done your chances good luck next time.")
donnee.counter += 1
Thank u in advance hope u help me with that and excuse my english if it wasn't that good :) :)
1.Error
You're calling the methods on the class penGame, not on a instance of penGame.
This causes your missing argument error because the method needs an instance of the class (the self parameter) but don't get one.
Instead use your variable (from the second solution):
if mygame.check(letter):
print("You cant use more one letter or numbers, try again !")
else:
mygame.game(letter, random_word)
...
Replace penGame with mygame also in the other calls.
Error
Save the result of the call in a variable and you won't need to recreate it.
mygame = penGame() # call the constructor
This line can then be removed:
myObject = penGame() # that causes the init to run again because it creates a new instance!

How to Type a Word Into an Input, and Then Have Python Search for a Variable Named That in a Module?

Sorry about the long title but I can't think of a better way to word this. I'm creating a basic sort of A.I. program, and one thing I want it to do is be able to define words, like a dictionary. Now I would use a python dictionary, but I want the database to stay intact after the program is finished, hence the reason I'm using a module. I also want the program to add to the module if the word isn't already defined.
Here's the part of the program I was using, but I'm stuck at this point:
from nouns import *
def search():
try:
print(nouns.(eval(definer)))
#This gives me a syntax error
except NameError:
define = input("I do not know what this is. Define it for me please: ")
n = open("nouns.py","a")
n.write("\n")
n.write(definer)
n.write("=")
n.write("\"")
n.write(define)
n.write("\"")
n.close()
print("You will have to restart the program before it recognizes the new definition.")
asking()
def asking():
global words
thewords = input("What do you want to talk about next?\n")
words = thewords.lower()
main()
def main():
global definer
defining = ("what is a ")
if defining in words and ("?") in words:
definerr = str(words[10:-1])
definer = definerr.lower()
search()
defining = ("what is ")
if defining in words and ("?") in words:
definerr = str(words[8:-1])
definer = definerr.lower()
search()
defining = ("what is a ")
if defining in words:
definerr = str(words[10:])
definer = definerr.lower()
search()
defining = ("what is ")
if defining in words:
definerr = str(words[8:])
definer = definerr.lower()
search()
asking()
So, how do I type a word into an input, then have python search for a word named that variable, and finally have python print that variable in the original program?
You need to store your objects in file or something similar. If you want you dictionary to be editable from outside the application I'd recommend json, if you want it to only be editable from with your application, use pickle. I'll give a json example:
words.json:
{
'thing': 'some object'
}
python:
import json
with open('words.json') as f:
words = json.load(f)
print words['thing']
... # Your program here, then as a final act before finishing
with open('words.json', 'w') as f:
json.dump(words, f)
Some code to get you started using the json module and in-memory dict editing:
#!/usr/bin/env python
import json
import os
FILE = "defs.json"
# load file (if exists...)
if not os.path.exists(FILE):
defs = {}
else:
with open(FILE) as defs_file:
try:
defs = json.load(defs_file)
except ValueError:
# invalid file - replace it with valid empty file
defs = {}
# do stuff...
defs['new definition'] = 'new value'
# save dict to the file
with open(FILE, 'w') as defs_file:
json.dump(defs, defs_file)

Searching text file for a words not working and not throwing any errors

Im trying to search a text file i have for an employees name and it doesn't seem to working but it also isn't throwing any errors. Whenever i search for a word in this file it gets inside the get_the_info function but never reaches the for loop it seems. Im assuming this because ive used print statements to try and figure out where the problem is. Im new to programming but i assume that is common convention to figure out some issues? Anyway heres the code:
import os
import sys
class find_employee:
def __init__(self):
self.get_the_info()
def get_the_info(self):
print "inside get info funct"
self.naples_empschedule = open("schedule.txt","r+")
self.read_schedule = self.naples_empschedule.readlines()
self.name = raw_input(" Enter your first and last name please ")
for line in self.naples_empschedule:
print " now inside for loop"
self.values = aline.split()
if self.name in line:
print ("Name:", self.values[0,1],"\n", "Position:", self.values[3],"\n", "Total Hours:", self.values[11])
else:
print ("You dont work here")
find_employee()
You're mixing classes and functions. Try this instead:
class EmployeeFinder(object):
def __init__(self, path_to_schedule, name=None):
self.name = name or raw_input("Enter your first and last name please: ")
self.path_to_schedule = path_to_schedule
def get_the_info(self):
with open(path_to_schedule, "r") as schedule_file:
for line in schedule_file:
values = line.split()
if self.name in line:
print("Name: " + values[0:1] + "\n" + \
"Position: " + self.values[3] + "\n" \
"Total Hours: ", self.values[11])
# note that this still won't work because values[0:1]
# will return a list, not a string. You might need
# ' '.join(values[0:1]).
else:
print("You don't work here")
employeefinder = EmployeeFinder("path/to/schedule/file", "Adam Smith")
employeefinder.get_the_info()
However it looks like you'd probably be better off with a function, rather than trying to force objects on this. Functional programming is NOT a bad thing.
def find_employee(path_to_schedule, name):
with open(path_to_schedule, "r") as schedule_file:
for line in schedule_file:
if name in line:
values = line.split()
new_name = ' '.join(values[0:1]) # I'm guessing at your intent
position = values[3]
hours = values[11]
print("Name: {}\nPosition: {}\nTotal Hours: {}".format(
new_name, position, hours))
(my last example uses string formatting which is a much better solution than string concatenation)
self.values[0,1]
Here you are trying to index a list with a tuple (0,1) which throws an error. Instead use
self.values[0]
or
self.values[1]
depending on which item you want from the list.
I think your for line in self.naples_empschedule:
should be for line in self.read_schedule:.

Categories