Value error: could not convert str to float PYTHON - python

Here is my code. I don't get why I get this error and how to correct it.
The error appears at: totals = entrant + float(tot)
here is my full code:
def total():
File = open("argent.txt","r")
File = File.read()
tot = File
print("You have",tot,"£ in your account")
def add():
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
add()
Thanks in advance.

In your case the function read() read not only characters 20 but also a new line character(s) appended to it.
So the variable tot contains the value which is not convertible to a number.
Try
tot = tot.strip()
before using it.

In the future, try avoid using File for file type variables.
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
By using with open the file is close after the following code.
Edit: Fixed the 'w' to file output from float to str

Related

How do i read from a csv file I created

I'm a self taught programmer and im trying to make a ticketing system in Python with csv. However, the reading function doesn't seem to be working after trying out different solutions.
The output I get is:
['Name\tAge\tGender']
[]
['as\t12\tf']
[]
The desired output id like to get is:
Name Age Gender
Jack 25 Male
I've attached the code of this program below. Any help would be greatly appreciated. Thank you.
import sys, select, os, csv
from os import system
def option_1():
with open(input("\nInput file name with .csv extension: "), 'w+') as f:
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append(name)
age = str(input("\nAge: "))
age_l.append(age)
sex = str(input("\nGender: "))
sex_l.append(sex)
field_names = ['Name', 'Age', 'Gender']
writer = csv.DictWriter(f, fieldnames = field_names, delimiter = '\t')
writer.writeheader()
writer = csv.writer(f, delimiter = '\t')
for row in [p]:
writer.writerow([name, age, sex])
def option_2():
with open(input('Input file name with .csv extension: '), 'a+') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append([name])
age = int(input("\nAge: "))
age_l.append([age])
sex = str(input("\nGender: "))
sex_l.append([sex])
writer = csv.writer(f, delimiter = '\t')
for row in [p]:
writer.writerow([name, age, sex])
def option_3():
with open(input("\nInput file name with .csv extension: "), 'r') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
f_reader = csv.reader(f)
for row in f_reader:
print(row)
def main():
system('cls')
print("\nTicket Booking System\n")
print("\n1. Ticket Reservation")
print("\n2. Append to an existing file")
print("\n3. Read from an existing file")
print("\n0. Exit Menu")
print('\n')
while True:
option = int(input("Choose an option: "))
if option < 0 or option > 3:
print("Please choose a number according to the menu!")
else:
while True:
if option == 1:
system('cls')
option_1()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 2:
system('cls')
option_2()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 3:
system('cls')
option_3()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
else:
exit()
if __name__ == "__main__":
main()
When writing data to the file, you explicitly change the default behavior of the csv writer to use tabs as the field delimiter. A similar instruction should be passed to the reader as well, so it knows how to separate between the values in each row. The output you are seeing is a result of the reader's default behavior - it looks for commas to distinguish between each value, but as it finds none, it treats the entire row as a single value, and includes the tab character (\t) as part of the value itself. Instructing the reader to use the same delimiter used for writing the file would allow it to properly parse each field as its own value.
Once the values are properly parsed, you'll notice that the output is still not quite as you desire; the object that is printed in print(row) is actually a list of the items in that row, which is why the output you see now is enclosed with square brackets ([]) for each printed line. Regardless of how the file is stored, you will need to format the output when printing it as required. There are many ways to do so, following is just one possibility:
f_reader = csv.reader(f, delimiter = '\t')
for row in f_reader:
print('\t'.join(row))
According to csv.reader docs:
Each row read from the csv file is returned as a list of strings.
So what you are seeing is the expected behavior. You can join the list of strings with ', '.join(row) if you like.

How to add numbers to a file

I'm a beginner at Python and I just learned about opening files, reading files, writing files, and appending files.
I would I like to implement this to a little project that I'm making that asks for the user's name and appends it to a txt file named "HallOfFame.txt"
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.read()
print(file_contents)
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + '\n')
name_file.close()
Everytime someone adds their name, I'd like it to become something like this:
Vix
Mike
Valerie
Something similar like that (above) where they have to run the program again to see the Hall of Fame.
Thank you!
I can understand your question. you can try using the JSON module and do something like this.
import json
list = [1, "Vix"]
with open ('HallOfFame.txt', 'w') as filehandle:
json.dump(list, filehandle)
here you can update the list every time you get input. and write it to the text file. but the appearance will look like this.
[1, "Vix"]
[2, "Mike"]
[3, "Valerie"]
count = 0
try:
infile = open('HallOfFame.txt', 'r')
file_contents = infile.readlines()
if len(file_contents) != 0:
print("\nHall of Fame")
for line in file_contents:
count += 1
print("{}. {}".format(count, line.strip()))
print()
infile.close()
except:
FileNotFoundError
print("No Human Has Ever Beat Me... mwah-ha-ha-ha!")
name_file = open("HallOfFame.txt", 'a')
name_record = input("Please enter your name: ")
name_file.write(str(name_record) + "\n")
name_file.close()

Python code isnt printing contents of txt?

elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")

Python file read and save

I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]

Writing text (from a variable) into a file and on a new line in Python

def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")

Categories

Resources