This question already has answers here:
Print string to text file
(8 answers)
Closed 6 years ago.
In class we are working on functions that calculate the area of a square or rectangle. The program asks for a person's name, what shape they want and what the length and width are. It then prints the area of that shape, and the program loops back around again. What I'm looking to do is take each individual name input and area and output them into a text file. Our teacher didn't make it too clear on how to do this. Any help would be appreciated. Here's the code:
import time
def area(l, w):
area = l * w
return area
def square():
width = int(input("please enter the width of the square"))
squareArea = area(width, width)
return squareArea
def rectangle():
width = int(input("please enter the width of the rectangle"))
length = int(input("please enter the length of the rectangle"))
rectangleArea = area(length, width)
return rectangleArea
def main():
name = input("please enter your name")
shape = input("please enter s(square) or r(rectangle)")
if shape == "r" or shape =="R":
print ("area =", rectangle())
main()
elif shape == "s" or shape == "S":
print ("area =", square())
main()
else:
print ("please try again")
main()
main()
Edit: I don't think I asked the question clear enough, sorry. I want to be able to input something, e.g. the name and be able to put it into a text file.
Easy way:
file_to_write = open('myfile', 'w') # open file with 'w' - write permissions
file_to_write.write('hi there\n') # write text into the file
file_to_write.close() # close file after you have put content in it
If you want to ensure that a file is closed after you finished all operations with it use next example:
with open('myfile.txt', 'w') as file_to_write:
file_to_write.write("text")
This is what you're looking for. The line file = open('file.txt', 'w') creates a variable file, in which the file object representing 'file.txt' is stored. The second argument, w, tells the function to open the file in "write mode", allowing you to edit its contents.. Once you have done this, you can simply use f.write('Bla\n') to write to the file. Of course, replace Bla with whatever you'd like to add, which can be your string variable. Note that this function doesn't make a newline afterwards by default, so you'll need to add a \n at the end if that's what you want.
IMPORTANT: As soon as you're done with a file, make sure to use file.close(). This will remove the file from memory. If you forget to do this, it won't be the end of the world, but it should always be done. Failure to do this is a common cause of high memory usage and memory leaks in beginner programs.
Hope this helps!
Edit: As MattDMo mentioned, it is best practice to open a file using a with statement.
with open("file.txt", 'w') as file:
# Work with data
This will make absolutely sure that access to the file is isolated to this with statement. Thanks to MattDMo to for reminding me of this.
Related
I am doing a simple project for my first python course and I am stuck in one part which I have no idea how to continue.
So in this part user should input a vehicle id that he/she wants to rent. After putting the vehicle ID, my code starts to search for that vehicle ID in the Vehicle.txt text file. If the code finds the VehicleID variable and also finds that it is "A" (which means available), it starts printing details for that specific car.
My Vehicle.txt text file looks like this;
XJY-604,Hyundai Getz,O,0,45.00,A
AJB-123,BMW mini,P,200,65.00,A
WYN-482,Ford Fiesta,O,0,40,A
BKV-943,Ford Ikon,P,150,60,A
JMB-535,Ford Flex,O,0,50,A
FKI-232,Fiat Egea,O,0,30,A
KLE-154,Toyota Corolla,O,0,40,A
ITO-444,Renault Clio,O,0,55,A
MAA-321,Honda Civic,O,0,70,A
IRK-948,Hyundai i20,O,0,30,A
TRY-475,Peugeot 2008,O,0,50,A
IBM-984,Skoda Superb,O,0,60,A
KRI-365,Opel Corsa,O,0,50,A
PMA-760,Citreon C3,O,0,55,A
NGT-407,KIA Sportage,O,0,60,A
So until this far, everything is fine; if the code finds the Vehicle ID (and the condition "A") then the code starts to print details as I want (if the condition is different or vehicle ID is not found it also prints appropriate error massages which are also perfectly working as I want).
My problem starts after this part:
After printing the details from the car, my code should change that specific car's condition from "A" (available) to "R" (rented) in the Vehicle.txt text file.
For example, let's say the user entered the Vehicle ID TRY-475 --> After this input, my excepted change in the Vehicle.txt text file is;
excepted change
But the actual change in the text file is;
actual change
My code looks like this;
from datetime import datetime
now = datetime.now()
dateandtime = now.strftime("%d/%m/%Y %H:%M:%S")
def rentVehicle():
VehicleID = input("Please enter the vehicle ID you want to rent: ")
with open("Vehicle.txt","r+") as f1:
for line in f1:
l = line.split(",")
if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
renterID = input("Please enter your ID: ")
startingodometer = input("Please enter the current odometer reading: ")
print("\nCar",l[0],"is rented to", renterID,"\n")
print("\t\t******************** Vehicle Details ********************\n")
print("Vehicle ID =",l[0],"\t\tDescription =",l[1],"\t\tDaily Rate =",l[4],"\tStatus =",l[5],"\n")
print("Renter ID =",renterID,"\tDate/time of rent =",dateandtime,"\tRent Starting Odometer =",startingodometer)
f1.write(l[5].replace(l[5],"R\n"))
print("\nRenting vehicle is successful!")
break
elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
break
else:
print("\nThe vehicle ID you entered does not exist. Please enter a valid vehicle ID.")
break
rentVehicle()
I think the problem is in line 17 ( f1.write(l[5].replace(l[5],"R\n"))). I searched for the other options but they also didn't give my excepted output in the Vehicle.txt text file. Additionally, I am not allowed to change my file name or add these lines to another file (manually or in the code) as it is restricted in my project work. I should only update the current Vehicle.txt via code. I would be very glad if someone solve this. For a beginner, these problems are really challenging sometimes. Thanks in advance.
the problem in your code is here:
with open("Vehicle.txt","r+") as f1:
for line in f1:
l = line.split(",")
if l[0] == VehicleID and l[5] == "A\n" or l[5] == "A":
renterID = input("Please enter your ID: ")
startingodometer = input("Please enter the current odometer reading: ")
~~~~~~~~~~~~~~~~~~~
f1.write(l[5].replace(l[5],"R\n"))
~~~~~~~~~~~~~~~~~~~
break
elif l[0] == VehicleID and l[5] == "R\n" or l[5] == "R":
print("\nThe vehicle you entered is rented. Please display available cars from the main menu.")
break
else:
print("nothing found")
break
I supposed that you are not very familiar with how does the file reading work on the background ... To put it simply, there is a buffer of a specific length (for example 1028B) whihc means it is going to read 1028B of text. The reason why it is this way is that you are unable to efficiently know, how long the line will be, and also reading from a file is slow, therefore reading as much as possible in the shortest time possible is what everyone is aiming for.
Now to your code, what happend there is that your whole file got loaded into the mentioned buffer and a file pointer ended up at the end of the file.
What you should do and is recommended to do is not to rewrite the file you are currently reading (you can check out some articles about how files actually work, sorry I am not 100% sure right now whether it even lets you to write to a file that you are reading ...).
Therefore, what you need to do, is this (this is pseudocode, in order for you to do it yourself, to gain more experience :)):
with open("Vehicle.txt","r+") as read_file:
with open("Vehicle2.txt","w+") as write_file:
for line in read_file:
if (your checks):
... (setting up)
write_file.write(f"{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{edited_thing}")
else:
write_file.write(line)
// after this, you can eighter rename these files or delete the original one and then rename the other one ther:
// vehicle.txt -> temp.txt ; Vehicle2.txt => Vehicle.txt ; delete temp.txt ?
I hope this answer helps and I wish you a nice programming journey ;)
EDIT:
I just noticed that you have multiple checks there. if you do not really need to break it, I recommend you using continue which will immediatelly start the next iteration.
import pickle
med = {}
medfile = open("Medicines.dat","wb")
while True:
name = input("Enter the name: ")
company = input("Enter the company: ")
chemical = input("Enter the chemical: ")
price = input("Enter the price: ")
med['name'] = name
med['company'] = company
med['chemical'] = chemical
med['price'] = price
pickle.dump(med,medfile)
ans = input("Wouldyou like to add more(y/n) ")
if ans == "y":
continue
elif ans == "n":
break
medfile = open("Medicines.dat","r+")
print(pickle.load(medfile))
medfile.close()
The question is as follows:
A binary file "Medicines.dat has structure [Name, Company, Chemical, Price] a) Write a user defined function add_data() to input the data for a record and store in the file b) Write a function search() which accepts a company name and displays the details of all the Medicines by that company
There are a few problems here:
1st Opening the file correctly
medfile = open("Medicines.dat","r+")
You mean rb. The difference is explained here, but pickle parsing requires the file to be in "binary" mode, hence the "b".
2nd Closing the file correctly
You should close the file before re-opening it for writing, as a matter of best practce. (medfile.close()). Even better, python will take care of when the file gets closed if you use the "with" syntax to create a context
3rd Having the right values
While the code should now run, I doubt it will do what you want. Your query asks "Wouldyou [sic] like to add more(y/n)", but it does not look to me like it is adding more values, since you use the same "med" dictionary over and over. Consider how the "new" fields would ever be distinguishable from the "old" ones, based on their key
i need to ask the user for an input (what problem do you have?)
i created a file that has the possible problems as well as possible solutions to these problems.the program should print out the solution if the user input mathces the keyword in the file. here is the code:
print ("welcome to our automated trouble shooting system")
def do_again():
datadict = {}
with open('prosol.txt') as file:
for rec in file:
rec = rec.split(':')
problem = rec[0]
answer = rec[1]
problem = problem.split(" ")
for item in problem:
datadict[item] = answer
user_problem = input('What is the problem?: ')
print(datadict[user_problem])
repeat = input("do you have any other problems.\n1. Yes\n2. No\n")
try_again = ["1","2"]
while repeat not in try_again:
repeat = input("do you have any other problems.(please answer using the corrinsponding numbers)\n1. Yes\n2. No\n")
if repeat == "1":
(do_again())
elif repeat == "2":
print("bye. i hope it helped you")
quit()
(do_again())
it works when i use one word keywords. for example
welcome to our automated trouble shooting system
What is the problem?: **screen**
if your screen is broken, then you will have to replace it. if it is frozen the try turning off your phone and the turn it on again.
do you have any other problems.
1. Yes
2. No
but it doesnt work if i put a full sentence.for example
welcome to our automated trouble shooting system
What is the problem?: **my screen doesnt work**
Traceback (most recent call last):
File "C:\Users\hp\Downloads\task2\mine\task 2.py", line 38, in <module>
(do_again()) ##calling the function
File "C:\Users\hp\Downloads\task2\mine\task 2.py", line 18, in do_again
print(datadict[user_problem]) ##print the value of the kye selected
KeyError: 'my screen doesnt work'
i feel like this is happening because i am using a dictonary. although i know this is the rerason , idont know how to fix it. can someone help me pls.
here is the file just in case you need it:
screen Screen SCREEN display Display DISPLAY : if your screen is broken, then you will have to replace it. if it is frozen the try turning off your phone and the turn it on again.
battery Battery BATTERY power Power POWER : if your phone is out of charge and you cant seem to charge it then you will have to replace either your battery or charger.
audio Audio AUDIO sound Sound SOUND : to fix you sound you can go to settings, then display. there you can change the setting of your devices sound
also i am a newbie at python. so you will have to bear with me with your explanations
You're calling a key directly from the user input. You need to search for the keyword before you try to call the key or you can put in a try except clause to catch exceptions where the key they're calling isn't in the dictionary.
user_answer = input("What's your problem?")
split_answer = user_answer.split(" ")
for option in datadict.keys():
if option in split_answer:
print(datadict[option])
The problem is that your dictionary has an entry for 'screen' (or '**screen**', I'm not sure judging by your code), but not for any complete sentence.
You need to identify the keywords that indicate problems in the user input first, then print the solutions stored by your dictionary.
Here is a simple demo that should get the point across.
>>> answers = {'screen': 'do A', 'water': 'do B', 'power': 'do C'}
>>> user_input = input('what is the problem? ')
what is the problem? my screen is damaged from a water spill
>>> words = user_input.lower().split()
>>> for problem in words:
... if problem in answers:
... print(answers[problem])
...
do A
do B
(I am assuming that you are using Python 3, if you are using Python 2 use raw_input instead of input.)
I'm guessing that your record file looks like:
question1:answer1
question2:answer2
...
question_n:answer_n
the error might lie in here:
def do_again():
datadict = {}
with open('prosol.txt') as file:
for rec in file:
rec = rec.split(':')
problem = rec[0]
answer = rec[1]
problem = problem.split(" ")
for item in problem:
datadict[item] = answer
The problem = problem.split(" ") just split a whole sentence into words, and the datadict only stores those words as keys.
for example:
how old are you:16
In your code, the datadict is like :
{
'how': 16,
'old': 16,
'are': 16,
'you': 16
}
which is not what you want
So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.
In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively
First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.
Forgive me if this comes out a bit scatter-brained, I'm not exaggerating when I say I've been working on this program for over 13 hours now and I am seriously sleep deprived. This is my 4th revision and I honestly don't know what to do anymore, so if anyone can help me, it would be greatly appreciated. My introduction to programming teacher wanted us to make a "flash card" study program from his template. I am using Idle 3.3.3 on a windows 7 machine.
#Flash Cards
#Uses parallel arrays to store flash card data read from file
#Quizzes user by displaying fact and asking them to give answer
import random
def main():
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
keepGoing = "y"
while keepGoing == "y" or keepGoing == "Y":
#Enter your code below this line
# 2a. Pick random integer between 0 and numCards and store the
# number in a variable named randomPick.
randomPick = random.randint (0, numCards)
# 2b. Add one to the totalTried accumulator variable.
totalTried = totalTried + 1
# 2c. Print element randomPick of the fact array. This shows the
# user the fact/definition for this flashcard.
print (fact [randomPick] )
# 2d. Prompt the user to input their guess and store the string they
# enter in a variable named "userAnswer"
userAnswer = input ('What is your answer?' )
# 2e. Compare the user's guess -userAnswer- to element
# -randomPick- of the answer array.
if userAnswer == (answer [randomPick]):
# 2e-1 If the two strings are equal, tell the user they
# guessed correctly and add 1 to the totalRight
# accumulator variable.
print ('That is correct.')
totalRight == totalRight + 1
# 2e2. If the two strings are not equal, tell the user they guessed
# wrong and display the correct answer from the answer array.
else:
print ('That is incorrect.')
print (answer [randomPick])
#2f. Prompt the user the user to see if they want to continue and
#store their response in the keepGoing variable.
keepGoing = input ('Would you like to continue?')
#Enter your code above this line
print("You got", totalRight, "right out of", totalTried, "attempted.")
def loadCards(answer, fact):
#Enter your code below this line
# 1a. Open flashcards.txt in read mode & assign it var name "infile"
infile = open('flashcards.txt', 'r')
# 1b. Read 1st line from file and store in var. name "line1"
line1 = infile.readline ()
# 1c. Use while loop to make sure EoF has not been reached.
while line1 != '':
# 1c1. Strip newline escape sequence (\n)from variable's value.
line1 = line1.rstrip ('\n')
# 1c2. Append string to answer array.
answer.append (line1)
# 1c3. Read next line from file and store in var. name "line2"
line2 = infile.readline ()
# 1c4. Strip newline escape sequence (\n) from variable's value.
line2 = line2.rstrip ('\n')
# 1c5. Append the string to the fact array.
fact.append (line2)
# 1c6. Read next line from file and store it in var. name "line3".
line3 = infile.readline ()
# 1d. Close file.
infile.close()
#Enter your code above this line
main()
When I run the program nothing actually happens, but when I try to close the shell window afterwards, it tells me that the program is still running and asks if I want to kill it.
Debugger shows me no information when I try to check it, also.
However, if I copy the code into the shell and run it from there, I get "SyntaxError: multiple statements found while compiling a single statement". Neither file has changed, but earlier it was telling me there was a problem with "import random".
Thanks in advance for any help.
I took a quick look and it mostly seems okay to me. I changed input() to raw_input() (two of them in your code) and noticed you had a double equals when you probably meant a single one
line 36:
totalRight == totalRight + 1
changed to
totalRight = totalRight + 1
which fixes your correct answer counter and line 68:
line3 = infile.readline ()
changed to
line1 = infile.readline ()
else it gets caught in your while loop forever. And I just copied line 54:
line1 = infile.readline ()
and pasted it so it is there twice to add another readline() call, just a lazy way of skipping the first line in your text file, since it seems to be a comment and not part of the answers and questions. You probably don't want to do that and just remove the comment from your text file. =b
With those changes, it seems to work fine for me.
Since this is for a class (and I can't only comment, I can just answer) I want to add that there actually is such a thing as too many comments
These comments (and to be honest, most of your comments) are distracting and unnecessary
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
Also, the whole point of putting your program inside of a function called main is so you can run that function only if you are calling that file directly and you should probably put
if __name__ == '__main__':
main()
at the bottom of your code instead of just
main()
Use of input() is generally considered dangerous (unless you're using Python3 or later where it is the same as raw_input()) due to the fact that it evaluates the input. You should handle the type yourself with something like, if you want an integer,
foo = int(raw_input('Input a number: '))
(Note that the return of raw_input is a string, so if you want a string you don't have to do anything)