I am new to python and having some trouble outputting my data into a csv file. the script runs but the file is blank that is created with no data.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
You may just have some extra indentation. Here's the same script but some indentation has been removed on lines 19 and 20.
#!/usr/bin/env python3
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
There's an else missing. Your input is not appending anything to shop_list and thus nothing gets written to the file.
import os
import smtplib
import csv
os.system('clear')
class CreateList(object):
def add_items(self):
shop_list = []
print("Lets create a shopping list for you..\n")
print("Please enter DONE when you have all the items needed for your shopping list.")
while True:
add_item = input("> ")
if add_item == 'DONE':
break
else: # <<< missing
shop_list.append(add_item)
print("Here is your current shopping list:")
csv = open('shoplist.csv', 'w')
for item in shop_list:
print(item)
csv.write(item + '\n')
csv.close()
c = CreateList()
c.add_items()
Related
I have a text file named universitylist.txt. When the user's input matches the college name, the college and city are returned. I am trying to add an IF statement that will return a random entry from the file when the user enters "random college". I am searching for the best way to do this. I tried appending random.LineItem in the print statement but that doesn't work.
e#!/usr/bin/env python3
from random import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
**if user_input == "random college":
rando_entry = random.schoollist_dict(lineitem)
print(rando_entry)**
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__": main() # Main entry point for the applications
nter code here
Add this to your code,
import random #goes on top
random.choice(list(schoollist_dict.values()))
So something like this,
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
Make sure you import random on top.
I created a textfile with 2 columns and the code above works for me when I updated your code with it.
Your final code should look like this,
import random
def main():
print("Welcome to University Locator!")
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
city = ""
while user_input.lower() != "x":
with open("universitylist.txt") as file:
schoollist_dict = {}
for lineitem in file:
lineitem = lineitem.replace("\n", "")
school_city_list = lineitem.split(",")
schoollist_dict.update({school_city_list[0]: school_city_list[1]})
user_college = user_input.title()
if user_input == "random college":
rando_college, rando_city = random.choice(list(schoollist_dict.items()))
print(rando_college, rando_city)
elif user_college in schoollist_dict:
print()
print(f"College: {user_college}")
print(f"City: {schoollist_dict[user_college]}")
print()
else:
print(f"The college {user_college} does not exist in our database.")
print()
user_input = input("Please enter the the name of the university or type 'random college'(press x to exit). ")
print("Session Terminated")
if __name__ == "__main__":
main() # Main entry point for the applications
I had a basic phone book application that adds, lookup, updates, and deletes a record and it works fine. I wanted to add functionality to it in which when I close and restart the program the previously added records are still there saved in a file. And when I want to add more records to the dictionary file it will also be appended to the file but I am running into 2 issues the first one is when I try to integrate my saved file with my dictionary I get error dictionary update sequence element #0 has length 1; 2 is required so I for some reason can't read the file to check if I have a record in the file with the same name for example. The second issue is when I Quit the program I added a save Record function which when run adds the newly added records onto the file to save it before it quits but when I print it, it only shows the first string printed the other is not shown I don't know what is causing this. Any help is appreciated thanks in advance.
#!/usr/bin/python3
import os.path
from os import path
phones = {}
if path.exists('phones.txt'):
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
else:
phoneFile = open("phones.txt", "w")
print("File Created")
phoneFile.close()
with open("phones.txt") as f:
phones = dict(x.rstrip().split(None, 1) for x in f)
def menu():
print("1. Add a record")
print("2. Lookup a record")
print("3. Update a record")
print("4. Remove a record")
print("5. List all records")
print("6. Quit")
selection = input("Please make your selection from the options above: ")
if(selection == '1'):
addRecord()
menu()
elif(selection == '2'):
lookupRecord()
menu()
elif(selection == '3'):
updateRecord()
menu()
elif(selection == '4'):
removeRecord()
menu()
elif(selection == '5'):
listRecords()
menu()
elif(selection == '6'):
saveRecords()
print("Goodbye")
#exit(0)
else:
print("Sorry, invalid input, try again.")
menu()
def addRecord():
a = str(input("Person's name to add to record: "))
b = int(input("Number to add to record: "))
if a in phones:
print("Name already in records, Please choose another name")
else:
phones[a] = b
print(phones)
def lookupRecord():
a = str(input("Person's name to look: "))
if a in phones:
print(a + "'s number is " + str(phones.get(a)))
else:
print("Person not found")
def updateRecord():
a = str(input("Person's name to update: "))
if a in phones:
b = int(input("New phone number to update: "))
phones[a] = b
print(phones)
else:
print(a + " is not in your phone book")
def removeRecord():
a = str(input("Person's name to remove: "))
if a in phones:
del phones[a]
print(a + " removed from phone book")
else:
print("Name not found")
def listRecords():
for i in phones.items():
print(i)
def saveRecords():
for i in phones.items():
writePhoneFile = open("phones.txt", "w")
finalRecord = ':'.join('%s' %id for id in i)
writePhoneFile.write(finalRecord)
readPhoneFile = open("phones.txt", "r+")
print(readPhoneFile.read())
def main():
print("== Welcome to the Phonebook App ==")
menu()
if __name__ == "__main__":
main()
use below because phone number in integer :
phones = dict( (x.rstrip().split(':')[0] , int(x.rstrip().split(':')[1])) for x in f)
in addition, open the file outside for loop in saverecords:
writePhoneFile = open("phones.txt", "w")
for i in phones.items():
print(i)
finalRecord = ':'.join('%s' %id for id in i)+'\n'
writePhoneFile.write(finalRecord)
writePhoneFile.close()
#!/usr/bin/env python3
import csv
# a file in the current directory
FILENAME = "contacts.csv"
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
def list_contacts(contacts):
for i in range (len(contacts)):
contact= contacts[i]
print(str(i+1) +"."+ contact[0])
print()
def view_contact(contacts):
pos = int(input("Number: "))
if not (pos-1)in range(len(contacts)):
print(str(pos) + ' not in list, try again')
view(contacts)
return
contact = []
print(name + email + phone+".\n")
print()
def delete_contact(contacts):
index = int(input("Number: "))
contact = contacts.pop(index -1)
write_contacts(contacts)
print(contact[0]+" was deleted.\n")
def add_contact(contacts):
name=input("Name: ")
email=input("Email: ")
phone=input("Phone number: ")
contact= []
contact.append(name)
contact.append(email)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
def display_menu():
print("Contact Manager")
print()
print("COMMAND MENU")
print("list - List all contacts")
print("view - View a contact")
print("add - Add a contact")
print("delete- Delete a contact")
print()
print()
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower() == "list":
list_contacts(contacts)
elif command.lower()== "view":
view_contact(contacts)
elif command.lower()== "add":
add_contact(contacts)
elif command.lower()== "delete":
delete_contact(contacts)
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")
if __name__ == "__main__":
main()
This all my code. I'm trying to figure out how to make the delete and view commands display an error message when the user enters a number that is invalid but it's not working. I'm also trying to view a contact when the user selects a specific number form list which would then display the email name and phone number of that selected number. I'm currently stuck
The errors im getting are
raceback (most recent call last):
, line 93, in
main()
, line 81, in main
view_contact(contacts)
, line 32, in view_contact
view(contacts)
NameError: name 'view' is not defined
I don't think you has a good start with list into cvs using append, anyway is your example.
You can use remove to remove your contact from list, see examples with list: http://www.thegeekstuff.com/2013/06/python-list
when the user select a specific number from list , just read by stepping to the number phone because you add with: name + email + phone.
adding an error message , use: try except finally
import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
#classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
I am trying to make some sort of simplified python, but hitting errors only on the CheckDetails() function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help?
You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
I have been working on this python issue for a while. I am in an intro level class and I am soooo stuck. Right now I am getting no errors but the program is not printing the data (from names.txt) or prompting me to search. any help would be appreciated. -thanks!
def main():
print("Last, \tFirst")
print
name_list = get_names()
print_list(name_list)
new_file(name_list)
search_list(name_list)
def get_names():
# open the data file
infile = open('names.txt', 'r')
# read all the lines from the file
name_list = infile.read().split('\n')
#close the input file
infile.close()
return(name_list)
#def print list
def print_list(name_list):
#print the data
for name in name_list:
print (name)
return(name)
#def new_file
def new_file(name_list):
outfile = open('sorted_names.txt' ,'w')
for item in name_list:
outfile.write(item + '\n')
outfile.close()
#def search_list
def search_list(name_list):
again = 'Y'
while again == 'Y':
name = input("What name would you like to look for? :")
try:
name_index = name_list.index(name)
print (name), (" was found in the list at index point: "), name_index
except ValueError as err:
print (name), (" was not found in the list.")
print ("Would you like to search for another name?")
again = input("Would you like to run the program again? [y/n]") == 'y'
# execute the main function
main()
Corrected version with minimum changes:
def main():
print("Last, \tFirst")
print
name_list = get_names()
print_list(name_list)
new_file(name_list)
search_list(name_list)
def get_names():
# open the data file
infile = open('names.txt', 'r')
# read all the lines from the file
name_list = infile.read().split('\n')
#close the input file
infile.close()
#print data read into memory
print(name_list)
return(name_list)
#def print list
def print_list(name_list):
#print the data
for name in name_list:
print (name)
return(name)
#def new_file
def new_file(name_list):
outfile = open('sorted_names.txt' ,'w')
for item in name_list:
outfile.write(item + '\n')
outfile.close()
#def search_list
def search_list(name_list):
again = 'Y'
while again.upper()== 'Y':
name = raw_input("What name would you like to look for? :")
try:
name_index = name_list.index(name)
print (name), (" was found in the list at index point: "), name_index
except ValueError as err:
print (name), (" was not found in the list.")
print ("Would you like to search for another name?")
again = raw_input("Would you like to run the program again? [y/n]") == 'y'
# execute the main function
main()
What changed:
in get_names, the name_list read was actually a string, not a list. To get the list of lines you need to split on the newlines (.split('\n')). After that you don't need to remove the newlines from the names
after get_names() returns, you need to store the list and pass to the other functions
new_file used name_list, but didn't receive it as argument
the try/except block should be nested in the while block
Congrats, it seems to be working (:
main() doesn't do much, it just prints a couple of lines. You will want to make it call your other functions.