Below is my python code:
filename = 'ToDo.txt'
def preview():
temp = open(filename, 'r')
print temp.read()
print '\n'
temp.close
def new_task():
temp = open(filename, 'a')
while True:
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close
I think it should display modified file with new entry saved if input is "preview", but it doesn't. Any idea to do the same.
EDIT2: Seeing the other answers, I realise your question may be interpreted in many different ways. The first part of my answer might or might not be the right one, but the second one is interpretation-neutral!
This answer assumes you are trying to see "preview" as the last line in your file.
It won't work because your are loading and printing the file before you saved it. Try substituting the relevant bit of your code with this:
if new_entry == 'preview':
temp.write(new_entry + '\n')
temp.close()
print '\n'
preview()
break
EDIT: If you are doing a lot of reading/writing/printing/previewing with your file, you might be interested in looking at the StringIO module. From the docs:
This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
The idea in this case would be that you do all your file handling in memory and before quitting the program you simply save the entire "memory file" to a "disk file". The reason to prefer this approach is that I/O operations on disk are expensive, so if you do this a lot you might bog your program down [I understand with a ToDo program this might not be the case, yet I though it was interesting to mention.
HTH!
You are not actually calling any of your functions:
filename = 'ToDo.txt'
def preview():
temp = open(filename, 'r')
print temp.read()
print '\n'
temp.close
def new_task():
temp = open(filename, 'a')
while True:
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close
new_task() //adding this line will call the new_task() function
In python to call a function you need to explicitly state it at the bottom of the py file
You should change your code to:
def new_task():
while True:
temp = open(filename, 'a')
new_entry = raw_input('Enter New Task: ')
if new_entry == 'exit' or new_entry == 'quit':
break
if new_entry == 'preview':
print '\n'
preview()
break
temp.write(new_entry + '\n')
temp.close()
Two changes here:
not temp.close, but temp.close()
temp = open(filename, 'a') moved inside the loop to be executed each time
The program has temp.close. This isn't the proper way to call close(); thus the temp.write doesn't get done immediately. You need temp.close().
Related
Im supposed to make a function for adding name and number to a.txt file, and one for reading the file. What am I doing wrong and how do I correct it? first post so I dont know if something is in the wrong format, sorry.
def add():
while True:
name = input("Name and number: ")
with open("Telefon.txt", "a") as f:
f.write(name)
f.close()
if name == "Enter":
break
def read():
f = open("Telefon.txt", "r")
print(f.read)
There are certain logical and optimizations mistake in your code you should not open file again and again and close it in loop, also use empty condition to terminate the loop e.g. press enter without entering any thing. For reading, I replaced your read method with redlines method
def add():
with open("Telefon.txt", "a") as f:
while True:
name = input("Name and number: ")
f.write(name + '\n')
if name == "":
break
def read():
f = open("Telefon.txt", "r")
print("".join(f.readlines()))
add()
read()
The output is following
So as the title suggests I'm trying to do a to-do list CLI app, and I've been getting that error. (NameError: name 'loaded_uinput' is not defined)
When I set loaded_uinput to a global variable it gives me that error, but if I don't it gives me this one: UnboundLocalError: local variable 'loaded_uinput' referenced before assignment
I've been trying to research all day looking for what I have been doing wrong, but aside from it being badly written code (for now, I'm planning on refactoring it really soon), I can't find it :/
userlist = []
filename = "userdata.p"
def maininput():
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in, encoding='bytes')
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "ab")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*loaded_uinput, sep="\n")
elif init_conf == "exit":
break
maininput()
I just want this to run without errors haha, don't even understand how it's saying that it isn't defined when it really seems like it is :/
I want to write something and have that be stored in userdata.p
Thank you!
Do not define loaded_uinput as a global variable outside of the function. The UnboundLocalError appears if you try to use loaded_uinput before it is defined, which can happen if init_conf == "write" is True in the very first iteration of the while loop. That is, if you type "write" the very first time, loaded_uinput will not be defined when it tries to use it for the printout.
The error is occurring because you are trying to access the loaded_uinput variable before assigning any value to it.
When the loop runs for the first time and 'write' command is entered, the loop gets the gets the data input to uinput and save it to file but tries to print print(*loaded_uinput, sep="\n") which is not yet assigned. It should be changed to:
print(*uinput)
open(filename, "ab") was changed to replace the file's contents instead of appending to it.
open(filename, "wb")
Check this working code:
import pickle
userlist = []
filename = "userdata.p"
def maininput():
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in)
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "wb")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*uinput)
elif init_conf == "exit":
break
maininput()
Working example here: https://repl.it/repls/VapidDescriptiveMiddleware
You just need to define the variable before the loop. It is created only in the 'if' block scope, and not when you get to the 'elif' block, where you are trying to access it. You can set it to an empty list if you want.
userlist = []
filename = "userdata.p"
def maininput():
loaded_uinput = []
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in, encoding='bytes')
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "ab")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*loaded_uinput, sep="\n")
elif init_conf == "exit":
break
maininput()
The title pretty much says it all. Each of the little functions works on their own (I tested them in separate files) , but they don't work when put into the main function. What am I doing wrong? (The codeblock is really long, sorry about that)
The basic issue is that it doesn't move to executing the function when the option is selected, it just ends.
from sys import exit
def readFrom():
file = input('What file do you want to read from? (Please include extension)')
try:
infile = open(file, 'r')
line = infile.readline()
cleanLine = line.strip()
while line != '':
print(cleanLine)
line = infile.readline()
cleanLine = line.strip()
infile.close()
menu()
except IOError:
print('Sorry, that is not a valid file. It might not exist or might not be in the correct directory.')
def writeTest():
file = input('What file do you want to write to?')
outfile = open(file,'w')
addition = input('What would you like to write to the file?')
try:
addition = int(addition)
except:
print('Sorry, that is invalid.')
writeTest()
outfile.write(str(addition))
outfile.close()
menu()
def fileAppend():
outfile = open('example.txt','a')
addition = input('What would you like to add to the file?')
try:
addition = int(addition)
except:
print('Sorry, that is invalid.')
fileAppend()
outfile.write(str(addition))
outfile.close()
menu()
def menu():
print('Hello! Welcome to the file editing helper!')
answer = input('Selection Menu:\n'
'0. Exit\n'
'1. Read from file\n'
'2. Write integers to a file\n'
'3. Append integers to a file\n'
'Which would you like to do? ')
if answer == 1:
readFrom()
if answer == 2:
writeTest()
if answer == 3:
fileAppend()
if answer == 0:
exit()
menu()
I've tried it every way that I can think of, I've put the full functions into the segments where I'd otherwise call the functions, and if I didn't have to have them in functions per the requirements I've been given, I wouldn't have them in functions. Any tips are helpful because I am really bad at this.
Ok, in your menu() you ask for an input, you then compare that input against an integer, but your input is considered a string.
example:
user_input = input('Enter a number') # 7
user_input will be '7', not 7, so you can't say
if user_input == 7:
#do this
because it never will. So here is your menu fixed.
def menu():
print('Hello! Welcome to the file editing helper!')
answer = int(input('Selection Menu:\n'
'0. Exit\n'
'1. Read from file\n'
'2. Write integers to a file\n'
'3. Append integers to a file\n'
'Which would you like to do? '))
if answer == 1:
readFrom()
if answer == 2:
writeTest()
if answer == 3:
fileAppend()
if answer == 0:
exit()
menu()
I wrapped the input function in an int() method and that should work now.
1 is not equal to '1', which is what you're trying to do.
So, I'm trying to make something simple:
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
print("Here's your list:")
for item in shopping_list:
print(item)
Can I, instead of printing this, return the list to another file in order to display that file? I'm new to this and am not sure if that's possible (though everything is possible with code, right?). My goal is to get the list to display, and to be saved so I can access it anytime.
For starters, you'll need to put your code inside a function. Or else, you won't be able to "return" anything.
def foo():
....
return shopping_list
So, your code would be something like:
def foo():
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
And, you'd call your function like this:
my_shopping_list = foo()
Once the function returns, my_shopping_list is a list of shopping items, you are free to do as you please.
Also notice I removed the print statements from your loop. Please feel free to add them in if you need them, but I assume that's what you didn't want.
Now, when you say file, I assumed you just meant to somewhere else inside the same program. But if you do indeed want to call this function from another python script, here's what you'll do:
A.py:
def foo():
... # entire function definition here
B.py
import A
my_shopping_list = A.foo()
Create two python scripts. The first one houses your foo function. The second one calls it.
Alternatively, if you want to print your shopping list to an actual file (taking your words literally here), you'd do:
foo():
...
with open('cart.txt', 'w') as f:
for i in shopping_list:
f.write(i + '\n')
This writes your items to a file.
If you mean that you want to run the list to a text file outside of your python script you can do the following:
outfile = open(file, "w")
CODE
outfile.write(shoppping_list)
outfile.close()
You can try this way :
def func():
shopping_list = []
print("Enter 'done' to stop adding items.")
while True:
new_item = input("> ")
if new_item.lower() == "done":
break
shopping_list.append(new_item)
return shopping_list
if __name__ == '__main__':
print("Here's your list:")
outfile = open('test.txt', "w")
shopping_list = func()
# outfile.write(shopping_list)
for item in shopping_list:
# print(item)
outfile.write(item + "\n")
outfile.close()
hiddenWords = ['hello', 'hi', 'surfing']
print("Would you like to enter a new list of words or end the game? L/E?")
decision = input()
if decision == 'L':
print('Enter a new list of words')
newString = input()
newList = newString.split()
hiddenWords.extend(newList)
j = random.randint(0, len(hiddenWords) - 1)
secretWord = hiddenWords[j]
exit(0)
How do I permanently add the input of the user to the hiddenWords list so that next time I open the application the words the user has entered has been extended onto the hiddenWords list?
Thanks.
This Code is part of a main body of code.
When you write
hiddenWords = ['hello', 'hi', 'surfing']
You are, each time the program runs, defining the variable hiddenWords as ['hello', 'hi', 'surfing'] .
So no matter what you extend after this, every time the code runs the line above, it will redefine to that value.
What you are looking for actually is to use a Database, such as SQLite, to store values so that you can retrieve them at any time.
Also, you can save data in a file and read this everytime, which is a simpler way.
When your program exits, all variables are lost, because variables only exit in memory. In order to save your modification accross program executions (everytime you run your script), you need to save the data onto the Disk, i.e: write it to a file. Pickle is indeed the simplest solution.
I like json. This would be a possible solution:
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
print("added " + add)
except:
print("failed to write file")
If you want to add multiple words at a time use this.
import json
words = []
try:
f = open("words.txt", "r")
words = json.loads(f.read())
f.close()
except:
pass
print("list:")
for word in words:
print(word)
save = False
while True:
print("enter a word to add it to the list or return to exit")
add = raw_input() # for python3 you need to use input()
if add:
words.append(add)
print("added " + add)
save = True
else:
break
if save:
try:
f = open("words.txt", "w")
f.write(json.dumps(words, indent=2))
f.close()
except:
print("failed to write file")