Issue with "w" to output and a loop in python3 - python

I have an issue with the program i'm currently writing.
Here's the code:
def main():
print ("This program let you create your own HTML-page,\nwith the necessary tags allready included")
t = ("<!DOCTYPE html>", "<html>", " <head>", " </head>", "<body>", "</html>") #Spaces for the indentation in the HTML-code.
menu = input("Press 1 to enter the file name for the html-page\nPress 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
#with open(name + ".html", 'w') as doc:
#Here is the first problem, indenterror if uncommented, otherwise elif gets syntax error.
#And this is crucial to get the code into the HTML-document.
#The error without (with open(name + ".html", 'w') as doc:) will be "global name "doc" is not defined".
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
elif menu == "2":
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
doc.write(title)
print (t[3], file=doc) #</head>
menu = input("Press 3 to start entering code in body ")
elif menu == "3":
print(t[4], file=doc) #<body>
code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n")
doc.write('{0}\n'.format(code)) #For newline to get the HTML-code cleaner.
while code != "</body>":
code = input("")
doc.write('{0}\n'.format(code))
if code == "</body>":
print ("Congratulations! You have successfully created your own HTML-page by using this python program.")
print (t[5], file=doc) #</html>
#somewhere in the loop above is the second error, I want the </body> to end the program,
#but it loops line 25 (code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n"))
main ()
Now to the issues. As you can see I'm trying to write a menu for the user to choose from 3 different tasks. Everything they do is supposed to output to a .html document.
I have commented my problems in the code as you can see.
I can't figure out how to get the with open(name + ".html", 'w') as doc: without the indentation for elif getting messed up, or I simply get an syntax error for elif.
The second problem is my loop at the end. I want the command to exit the program as it also output the correct ending code for the .html document, but it loops code = input("Type </body> to finish your html-page and to close the program.\nEnter your code for body below:\n") and I can't figure that out aswell.

def main():
(...)
while True:
if menu == "1":
name = input("Enter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
menu = input("Press 2 to enter title for the HTML-page\nPress 3 to start entering code in body ")
(...)
doc.close()
main ()
You can open a file like so: doc = open(name + ".html", 'w'), but don't forget to close it when you're done with it, like so doc.close().

Here is a simple file-opening function. Of course, it needs to be tweaked for your specific needs. The "with" statement itself will close the file.
def cat(openfile): #Emulates the cat command used in the Unix shell#
with open(openfile) as file:
lines = file.readlines()
return ''.join(lines)
If you want to write to a file, use this function.
def write2file(openfile, WRITE): #openfile = filename to open #WRITE = the string you want to write to file
with open(openfile, 'w') as file:
file.write(str(WRITE))
To append/add text to a file:
def add2file(openfile, add):
with open(openfile, 'a') as file:
file.write(str(add))

Related

Displaying Specific Information from a List in using User Input - Python 3

Before I state my question I would like to start by saying that I am a beginner at Python programming. I am about half way through my first ever programming class. With that being said I have also researched and used the search engines to look for information on the topic I am working on but I have not found anything that has been either helpful or specific enough to my problem. I have looked through Stack Overflow including browsing the similar questions dialogue. My hope is that this will not be down voted or marked as a duplicate before I get any helpful information.
I am creating a contacts manager program that uses a list of contact names, email addresses, and phone numbers stored in a CSV file. My program should allow the user to display a list of all the contact names, add/delete contacts, and view specific contact information. I am having trouble with the final requirement. Everything else in the program is working and displaying in the console like it should. The code for the entire program is found below;
#!/user/bin/env python3
# Contacts Manager Program
#Shows title of program at start.
print("The Contact Manager Program")
print()
#Imports CSV Module
import csv
#Defines global constant for the file.
FILENAME = "contacts.csv"
#Displays menu options for user, called from main function.
def display_menu():
print("COMMAND MENU")
print("list - Display all contacts")
print("view - View a contact")
print("add - Add a contact")
print("del - Delete a contact")
print("exit - Exit program")
print()
#Defines write funtion for CSV file.
def write_contacts(contacts):
with open(FILENAME, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(contacts)
#Defines read function for CSV file.
def read_contacts():
contacts = []
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
contacts.append(row)
return contacts
#Lists the contacts in the list with the user inputs the "list" command.
def list_contacts(contacts):
for i in range(len(contacts)):
contact = contacts[i]
print(str(i+1) + ". " + contact[0])
print()
#List a specific contacts information when the user inputs the "view" command.
def view_contact(number):
#Adds contact to the end of the list when user inputs the "add" command.
def add_contact(contacts):
name = input("Name: ")
email = input("Email: ")
phone = input("Phone: ")
contact = []
contact.append(name)
contact.append(email)
contact.append(phone)
contacts.append(contact)
write_contacts(contacts)
print(name + " was added.\n")
#Removes an item from the list.
def delete_contact(contacts):
number = int(input("Number: "))
if number < 1 or number > len(contacts): #Display an error message if the user enters an invalid number.
print("Invalid contact number.\n")
else:
contact = contacts.pop(number-1)
write_contacts(contacts)
print(contact[0] + " was deleted.\n")
#Main function - list, view, add, and delete funtions run from here.
def main():
display_menu()
contacts = read_contacts()
while True:
command = input("Command: ")
if command.lower() == "list":
list_contacts(contacts)
elif command.lower() == "view": #Store the rest of the code that gets input and displays output in the main function.
view_contact(contacts)
elif command.lower() =="add":
add_contact(contacts)
elif command.lower() == "del":
delete_contact(contacts)
elif command.lower() == "exit":
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")
if __name__ == "__main__":
main()
I need the view_contact function to get a number as input from the user and then print the corresponding contact information that is related the the line number in the CSV file.
It looks like you storing contacts in form of lists in your .csv file. Use read_contacts to read all the contacts from that csv file, then get contact specified by number parameter. That's it.
def view_contact(number):
contacts = read_contacts()
specified_contact = contacts[number]
print("Name: ", specified_contact[0])
print("Email: ", specified_contact[1])
print("Phone: ", specified_contact[2])

Trying to load and edit a pickled dictionary, getting an EOFError

I'm trying to modify a trivia program found in a book as part of a tutorial; I need to save the name and score of the player using a pickled dictionary. I've already created the dat file using a separate program, to avoid reading from a file that doesn't exist.
This is the code for the trivia program.
#Trivia Challenge
#Trivia game that reads a plain text file
import sys
def open_file(file_name, mode):
"""Open a file"""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the triva file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
value = next_line(the_file)
return category, question, answers, correct, explanation, value
def welcome(title):
"""Welcome the player and get his or her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def saving(player_name):
import pickle
f = open("trivia_scores.dat", "rb+")
highscores = pickle.load(f)
if player_name in highscores and score > highscores[player_name]:
highscores[player_name] = score
pickle.dump(highscores, f)
elif player_name not in highscores:
highscores[player_name] = score
pickle.dump(highscores, f)
print("The current high scores are as follows:")
print(highscores)
f.close()
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
#Get the first block
category, question, answers, correct, explanation, value = next_block(trivia_file)
while category:
#Ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
#Get answer
answer = input("What is your answer?: ")
#Check answer
if answer == correct:
print("\nRight!", end=" ")
score += int(value)
else:
print("\nWrong!", end=" ")
print(explanation)
print("Score:", score, "\n\n")
#Get the next block
category, question, answers, correct, explanation, value = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("Your final score is", score)
return score
player_name = input("First, enter your name: ")
main()
saving(player_name)
input("\n\nPress the enter key to exit.")
The eponymous error occurs at this point:
def saving(player_name):
import pickle
f = open("trivia_scores.dat", "rb+")
highscores = pickle.load(f)
When the questions end, the program attempts to run the "saving" module, which (In theory) opens the trivia_scores.dat file, loads the highscores dictionary, checks to see if the player's name is in the dictionary, and if their current score is higher than the one in the file, it overwrites it.
But for some reason, when the program attempts to load the highscores dictionary, instead I get this error message.
EOFError: Ran out of input
I have never seen this error before. From some cursory googling, I got the impression that it has something to do with the program trying to read from an empty file. But that made no sense to me, since I specifically created a dat file using a different program to prevent that from happening: trivia_scores.dat is NOT an empty file. I even read from it with Python Shell to make sure.
What does this error mean, and why won't Python load the dat file?
Context: The book I'm reading from is Python for the Absolute Beginner, by Michael Dawson. This program and the challenge I'm trying to complete come from chapter 7. The program was running fine before I added the saving module.
Probably the original trivia_scores.dat file you wrote got corrupt (maybe you didn't call close() on it?). You should try creating a new file and adding a pre-populated dictionary to this file. Then try reading from this new file.

reading, writing, appending, and deleting files in python

here's my code, i could use your help.
My program is supposed to accept data input, create new text files,read and write into text files, append text into already existing text files, truncate and delete files.
Now the problem i have with my program is that the the part of the code that is supposed to append text, truncate the content of a text file and delete a text file is not working and the program does not return any errors during run time.
import os
from sys import argv
filename = argv
def menu():
holder = input("enter 1 to create new file or 2 to use existing ones\n")
if holder == 1:
dam = raw_input("Enter name of new text file:\n")+'.txt'
textfile = open(dam, 'w+')
happ = raw_input("\nPlease enter record into your new file\n\n")
textfile.write(happ)
textfile.close()
print "*******************"
print "*******************\n"
print "To view the content of your new file, enter 'yes' otherwise enter 'no' to exit"
gett = raw_input()
if gett == 'yes':
print "*******************"
print "\nyour inputted record is>>>\n"
display = open(dam)
print(display.read())
print'\n'
menu()
elif gett == 'no':
print ("\nOk, see you later. Have a nice day!")
print'\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
elif holder == 2:
filename = raw_input("Enter name of file:\n")+'.txt'
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
if entry == 7:
print ("Displayed below is the content of your file, continue to append more text at the bottom of the file.(text is limited to 3 lines)\n")
textfiles = open(filename, 'a+')
print (textfiles.read())
line1 = raw_input( )
line2 = raw_input( )
line3 = raw_input( )
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
elif entry == 8:
textfiles = open(filename, 'w')
print "Truncating the file..."
textfiles.truncate()
print "Done, truncated."
textfiles.close()
right = raw_input("Do you want to write into this file? Y/N : ")
if right == 'Y':
textfiles = open(filename, 'a+')
print "text is limited to 3 lines"
line1 = raw_input('\n')
line2 = raw_input()
line3 = raw_input()
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
else:
print "Ok have a nice day"
elif entry == 9:
print "Deleting the file..."
try:
os.remove(filename)
except OSError, e: #if failed, report it back to the user
print ("Error: %s - %s." % (e.filename, e.strerror))
print "Done, deleted."
else:
print "Error! wrong entry"
print '\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
menu()
This is the output it gives
enter 1 to create new file or 2 to use existing ones
2
Enter name of file:
test
Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : 8
Error! wrong entry
enter 1 to create new file or 2 to use existing ones
ANY HELP ON HOW TO MAKE THIS WORK?
You are using the function raw_input() for your variable entry at the line
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
Refering to the documentation of python2 (https://docs.python.org/2/library/functions.html#raw_input), the function raw_input return a String.
After, you are testing your variable entry against integer values. Since a String never equals an int, the test won't work. And your code fall in the last condition block which is "wrong input"
To fix this issue, you should use the input function like you did at the begining of your code (https://docs.python.org/2/library/functions.html#input):
entry = input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
or cast entry to int
entry = int(raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : "))

Python (latest version) Syntax Error

I wrote this sample program that is meant to open a text file (database1.txt) from the computer, and display the results that are currently in the file. Then prompt the use if their name is in the document, if it is it should print the contents of the text file then close, otherwise it should prompt the user to enter their first name, then the program writes the name into the same text document, then prints the contents of the text file again so that the user can see the new added data. I have typed the code, and somehow it keeps saying I have a syntax error. I checked a few times and I cannot fix the error. I was wondering if someone could take a look and if they might be able to explain the error to me. Thank you
#This program reads/writes information from/to the database1.txt file
def database_1_reader ():
print('Opening database1.txt')
f = open('database1.txt', 'r+')
data = f.read()
print data
print('Is your name in this document? ')
userInput = input('For Yes type yes or y. For No type no or n ').lower()
if userInput == "no" or userInput == "n"
newData = input('Please type only your First Name. ')
f.write(newData)
f = open ('database1.txt', 'r+')
newReadData = f.read()
print newReadData
f.close()
elif userInput == "yes" or userInput == "ye" or userInput == "y"
print data
f.close()
else:
print("You b00n!, You did not make a valid selection, try again ")
f.close()
input("Presss any key to exit the program")
database_1_reader()
print is a function in py3.x:
print newReadData
should be :
print (newReadData)
Demo:
>>> print "foo"
File "<ipython-input-1-45585431d0ef>", line 1
print "foo"
^
SyntaxError: invalid syntax
>>> print ("foo")
foo
statements like this:
elif userInput == "yes" or userInput == "ye" or userInput == "y"
can be reduced to :
elif userInput in "yes"

Writing multiple lines to file and then reading them with Python

I've just undertaken my first proper project with Python, a code snippet storing program.
To do this I need to first write, then read, multiple lines to a .txt file. I've done quite a bit of googling and found a few things about writing to the file (which didn't really work). What I have currently got working is a function that reads each line of a multiline input and writes it into a list before writing it into a file. I had thought that I would just be able to read that from the text file and add each line into a list then print each line separately using a while loop, which unfortunately didn't work.
After going and doing more research I decided to ask here. This is the code I have currently:
'''
Project created to store useful code snippets, prehaps one day it will evolve
into something goregous, but, for now it's just a simple archiver/library
'''
#!/usr/local/bin/python
import sys, os, curses
os.system("clear")
Menu ="""
#----------- Main Menu ---------#
# 1. Create or edit a snippet #
# 2. Read a snippet #
# 0. Quit #
#-------------------------------#
\n
"""
CreateMenu ="""
#-------------- Creation and deletion --------------#
# 1. Create a snippet #
# 2. Edit a snippet #
# 3. Delete a snippet (Will ask for validation) #
# 0. Go back #
#---------------------------------------------------#
\n
"""
ReadMenu="""
#------ Read a snippet ------#
# 1. Enter Snippet name #
# 2. List alphabetically #
# 3. Extra #
# 0. Go Back #
#----------------------------#
"""
def readFileLoop(usrChoice, directory):
count = 0
if usrChoice == 'y' or 'n':
if usrChoice == 'y':
f = open(directory, 'r')
text = f.read()
f.close()
length = len(text)
print text
print length
raw_input('Enter to continue')
readMenu()
f.close()
elif choice == 'n':
readMenu()
def raw_lines(prompt=''):
result = []
getmore = True
while getmore:
line = raw_input(prompt)
if len(line) > 0:
result.append(line)
else:
getmore = False
result = str(result)
result.replace('[','').replace(']','')
return result
def mainMenu():
os.system("clear")
print Menu
choice = ''
choice = raw_input('--: ')
createLoop = True
if choice == '1':
return creationMenu()
elif choice == '2':
readMenu()
elif choice == '0':
os.system("clear")
sys.exit(0)
def create():
os.system("clear")
name = raw_input("Enter the file name: ")
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
while os.path.exists(dire):
os.system("clear")
print("This snippet already exists")
name = raw_input("Enter a different name: ")
dire = ('shelf/'+name+'.txt')
print("File created\n")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
else:
print("File created")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
print text
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
def readMenu():
os.system("clear")
name = ''
dire = ''
print ReadMenu
choice = raw_input('--:')
if choice == '1':
os.system("clear")
name = raw_input ('Enter Snippet name: ')
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
choice = ''
choice = raw_input('The Snippet exists! Open? (y/n)')
'''if not choice == 'y' or 'n':
while (choice != 'y') or (choice != 'n'):
choice = raw_input('Enter \'y\' or \'n\' to continue: ')
if choice == 'y' or 'n':
break'''
readFileLoop(choice, dire)
else:
raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back
readMenu()
elif choice == '0':
os.system("clear")
print Menu
def creationMenu(): ###### Menu to create, edit and delete a snippet ######
os.system("clear")
print CreateMenu
choice = raw_input('--: ')
if choice == '1': ### Create a snippet
os.system("clear")
print create()
print creationMenu()
elif choice == '2':
os.system("clear") ### Edit a snippet
print ("teh editon staton")
raw_input()
print creationMenu()
elif choice == '3':
os.system("clear") ### Delete a snippet
print ("Deletion staton")
raw_input()
print creationMenu()
elif choice == '0': ### Go Back
os.system("clear")
######## Main loop #######
running = True
print ('Welcome to the code library, please don\'t disturb other readers!\n\n')
while running:
mainMenu()
######## Main loop #######
Tl;Dr: Need to write and read multiline text files
The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format e.g ['line1', 'line2', 'line3'] which is making it difficult to read as multilines because I can't get it to be read as a list, when I tried it added the whole stored string into one list item. I don't know if I'm writing to the file correctly.
OK, so the problem is with writing the file. You're reading it in correctly, it just doesn't have the data you want. And the problem is in your raw_lines function. First it assembles a list of lines in the result variable, which is good. Then it does this:
result = str(result)
result.replace('[','').replace(']','')
There are two small problems and one big one here.
First, replace:
Return[s] a copy of the string with all occurrences of substring old replaced by new.
Python strings are immutable. None of their methods change them in-place; all of them return a new string instead. You're not doing anything with that new string, so that line has no effect.
Second, if you want to join a sequence of strings into a string, you don't do that by calling str on the sequence and then trying to parse it. That's what the join method is for. For example, if your lines already end with newlines, you want ''.join(result). If not, you want something like '\n'.join(result) + '\n'. What you're doing has all kinds of problems—you forgot to remove the extra commas, you will remove any brackets (or commas, once you fix that) within the strings themselves, etc.
Finally, you shouldn't be doing this in the first place. You want to return something that can be passed to writelines, which:
Write[s] a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
You have a list of strings, which is exactly what writelines wants. Don't try to join them up into one string. If you do, it will run, but it won't do the right thing (because a string is, itself, a sequence of 1-character strings).
So, if you just remove those two lines entirely, your code will almost work.
But there's one last problem: raw_input:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
But writelines:
… does not add line separators.
So, you'll end up with all of your lines concatenated together. You need the newlines, but raw_input throws them away. So, you have to add them back on. You can fix this with a simple one-line change:
result.append(line + '\n')
To read multiple lines from a file, it's easiest to use readlines(), which will return a list of all lines in the file. To read the file use:
with open(directory, 'r') as f:
lines = f.readlines()
And to write out your changes, use:
with open(directory, 'w') as f:
f.writelines(lines)
fileList = [line for line in open("file.txt")]
While the previously mention idiom will work for reading files, I like mine. Its short and to the point.

Categories

Resources