List not defined even when defined in earlier cases - python

prompt = " Type add, show, edit, complete or exit: "
while True:
user_action = input( prompt.strip())
match user_action:
case "add":
todo = input("Enter a todo:") + "\n"
file= open("todos.txt", "r")
todos = file.readlines()
file.close()
todos.append(todo)
file= open("todos.txt", "w")
file.writelines(todos)
file.close()
case "show" | "display":
file=open('todos.txt', "r")
todos= file.readlines()
file.close()
for index, item in enumerate(todos):
item= item.strip("\n")
row = f"{index+1}-{item.capitalize()}"
print(row)
case 'edit':
number= input("Enter a number: ")
print(number)
new_todo= input("Enter new tod0:")
todos[int(number)-1]= new_todo
print(new_todo)
case "complete":
number = int(input("Number of the todo:"))
row=todos.pop(int(number))
print(row)
case "exit":
break
# # case whatever:
# # print("wrong message!!! Baaaka")
print('Bye!')
In above code, when entering new to dos and using complete, it shows following error:
File "C:\Users\HP\OneDrive\Desktop\python apps\app1.py", line 40, in <module>
row=todos.pop(int(number))
NameError: name 'todos' is not defined
n above code, when entering new to dos and using complete, it shows following error:
File "C:\Users\HP\OneDrive\Desktop\python apps\app1.py", line 40, in <module>
row=todos.pop(int(number))
NameError: name 'todos' is not defined

Related

What am I doing wrong with the CSV part of my code

So, in my python code I'm supposed to prompt the user for their name, address, and phone number and write that data as a line of comma separated values to the file using the directory and filename. Everything runs except the CSV part.
import os
import csv
def file_system():
"""Display information about users"""
direc = input("Enter name directory to save a file: ")
filename = input("Enter name of the file they want to save to the directory: ")
name = input("Enter your name : ")
address = input("Enter your address : ")
phone_number = input("Enter your phone number : ")
print (direc, filename, name, address, phone_number)
prompt = input()
if os.path.isdir(direc):
writeFile = open(os.path.join(direc,filename),'w')
writeFile.write (direc, + filename)
writeFile.close()
print("File contents:")
readFile = open(os.path.join(direc,filename),'r')
for line in readFile:
print(line)
readFile.close()
if prompt:
with open('Userdata.csv', 'a',
newline='') as outfile:
w = csv.writer(outfile)
w.writerow(name, address, phone_number)
print("File Updated")
else:
print("Directory doesn't exist, please enter again")
file_system()
The issue is with the evaluation of the if statement before the csv section.
run the code below twice, first time just pressing enter, second time typing something and then pressing enter...
prompt = input("input something:\n")
if prompt:
print("you got here")
else:
print("you didn't")
As you can see, when only pressing enter, the if statement becomes False...

How can i code for edit a character in a txt file with python

it keep stop run after asking the old code and also clear my roti canai file. So what can I do for it.(even is changing all the code)
def modify_roti_canai():
print("\n*-- Modify Roti Canai Menu --*\n")
file = open("roticanai", "r+")
print(file.read())
old_code = input("Enter a Item Code for Modifying (e.g. RC01): ")
if len(old_code) == 4:
new_code = input("New Food Item Code: ")
new_name = input("New Food Item Name: ")
new_price = input("New Food Item Price: ")
file.write(new_code + "," + new_name + "," + new_price + "\n")
else:
print("Item Code Not Existed, Please try again!")
file.close()
*inside my roticanai file is exist few of record:
RC01,ROTI CANAI KOSONG,1.60
RC02,ROTI CANAI SUSU,3.90
RC03,ROTI CANAI CHEESE,4.50
RC04,ROTI CANAI PLANTA,3.90
RC05,ROTI CANAI TISSUE,4.50
s is an empty string. If you are comparing the length(i.e 0) with 4, then if statement evaluates to False. It doesn't add data to "temp.txt" file. It will an empty file renamed as "roticanai".
Rename the filenames as required
**Use the same filename, no need of temp file
def modify_roti_canai():
print("\n*-- Modify Roti Canai Menu --*\n")
with open("test.txt", "r") as file:
#Gets each line of the file as list item
data = [line.rstrip() for line in file.readlines()]
print(data)
#separates codes from data
codes= [x.split(',')[0] for x in data]
print(codes)
old_code = input("Enter a Item Code for Modifying (e.g. RC01): ")
if len(old_code) == 4:
#removes the old code line from data using the index of entered code
data.pop(codes.index(old_code))
new_code = input("New Food Item Code: ")
new_name = input("New Food Item Name: ")
new_price = input("New Food Item Price: ")
new_data = f"{new_code},{new_name},{new_price}"
#appends new data to the data list
data.append(new_data)
#Writes the data list to file
with open('test.txt','w') as file:
for e in data:
file.write(e + '\n')
print(file.read())
else:
print("Item Code Not Existed, Please try again!")

Python beginner - using constant to open file traceback

I'm trying to start using constants in my project and this happened.
Traceback (most recent call last):
File "C:\Users\aletr\Desktop\Python projects\Restaurant software\r_0.py", line 39, in <module>
with constants.NAMES_R as f :
File "C:\Python30\lib\io.py", line 456, in __enter__
self._checkClosed()
File "C:\Python30\lib\io.py", line 450, in _checkClosed
if msg is None else msg)
ValueError: I/O operation on closed file.
I know is because the file it's been closed. But I don't understand how I was using the same code without constant and it would work perfectly.
constants:
F_NAMES = 'names.txt'
NAMES_R = open(F_NAMES, 'r+')
NAMES_W = open(F_NAMES, 'w+')
script:
import constants
with constants.NAMES_R as f :
f_n = f.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
name = input("""
\n - Insert name to logg in
\n - ADD to save new user
\n - LIST to see saved users
\n - REMOVE to delete a user
\n - EXIT to finish
\n - ...""")
lname = name.lower()
if lname == "add":
n_input = input("Name:")
with open('names.txt', 'a') as f:
f.write(n_input + '\n')
elif lname == "list":
with constants.NAMES_R as f :
print(f.read().splitlines())
f.close()
elif name in f_n:
print("Logged as", name.upper())
user = name
input('Welcome, press enter to continue \n')
break
elif lname == 'remove':
remove = input("Insert user name to remove \n ...")
with constants.NAMES_R as f :
lines = f.readlines()
lines = [line for line in lines if remove not in line]
with constants.NAMES_W as f :
f.writelines(lines)
elif lname == "exit":
exit()

NameError for filename?

I'm trying to write a program that assigns prices to a list, but I'm having trouble. I keep getting a NameError, that costlist is not defined. The program should ask for an input, append it to the list, and go through the whole list, then write it to the .txt file.
import os
def main():
if os.path.exists("costlist.txt"):
os.remove("costlist.txt")
print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
try:
file = open(filename, "r")
listie = file.readlines()
for item in listie:
print(item)
break
except FileNotFoundError:
filename = input("Sorry, that file wasn't found. Try again?")
if filename == "end":
exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
file.write(item.strip("\n"))
file.close()
for item in listie:
cost = input(print( item + "should cost how much?"))
try:
float.cost
except ValueError:
print ("You entered an invalid float that can't convert string to float:" + cost)
print ("Skipping to the next item after" + item)
print (item + "has a cost of" + cost + "dollars")
file = open(costlist.txt, "a")
file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
print (item)
print ("Program End")
You forgot to enclose the file name by quotes.
Change file = open(costlist.txt, "a") to file = open("costlist.txt", "a")
And
file = open (costlist.txt, "r") to file = open ("costlist.txt", "r")

Change text in file with Python

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Categories

Resources