I am trying to create two programs one that writes the data to file golf.txt and the second which reads the records from golf.txt and displays them. The first program I am trying to get the program to quit when you leave the input field blank. Here's my code for the first program.
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
score = input("Player's score(leave blank to quit):")
if input ==" ":
break
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
With the second program I can't get the program to display the output I want on one line. Here's the second program.
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
player = infile.read()
# reads the score array from the file
score = infile.read()
# prints the names and scores
print(player + "scored a" + score)
# closes the file
infile.close()
# calls main function
main()
Any help or suggestions I can get would be greatly appreciated.
Two main problems:
1.) you first code has if input == ' ' which is wrong in two ways:
input is a function. you already saved the input so you should be comparing with name and score.
input returns a '' when you dont input anything, not a ' '.
so change to: if name == '' or score == '': or even if '' in (name,score): (does the same things)
2.) file.read() will automatically read EVERYTHING in the file as one string. You want to split it into each component so you can either do something like:
player,score = file.readlines()[:2]
or
player = file.readline()
score = file.readline()
then print (with leading and trailing spaces in your middle string!)
print(player + " scored a " + score)
Got both programs working
program 1:
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
if name == "":
break
score = input("Player's score:")
#write to file golf.txt
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
program 2:
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " scored a " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
# calls main function
main()
Eliminate spaces from the input before checking (I would use .strip() method). And compare it to the empty string "" instead of space(s) " ".
With the "while true" block you keep asking and taking the names and the scores, but you overwrite them so you always will have just the last pair.
You need to keep them all, so you can make a list:
names_and_scores = []
while True:
name = input("Player's name(leave blank to quit):").strip()
if name == "":
break
score = input("Player's score:").strip()
if name != "" and score != "":
names_and_scores.append("{}; {}".format(name, score))
with open('golf.txt', 'w') as outfile:
outfile.write("\n".join(names_and_scores))
The second program opens the file, read lines one by one, splits them and print:
with open('golf.txt', 'r') as infile:
for line in infile:
name, score = line.strip().split("; ")
print("{} scored a {}.".format(name, score))
Related
I have a piece of code used to enter student information. But I want to transform it so that Admission no. cannot be repeated, when entering an existing number, a message will be printed if you want to re-enter an existing number. below is my code
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
student_data.append(value)
with open(student_database,"a",encoding = "utf-8") as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
return
You can do something like this. As Barmar suggested, put the admission numbers in a set at the start of your definition. Then, check the user's input against those numbers. Create a while loop that doesn't let the user input any other value until they enter a new Admission no (and tell them that they are entering a duplicate admission number). Once everything looks good, write it to the csv.
import csv
student_fields = ['Admission no.','Name','Age','Email','Phone']
student_database = 'students.csv'
def add_student():
print("-------------------------")
print("Add Student Information")
print("-------------------------")
global student_fields
global student_database
# create a set of the already entered admission numbers
with open('students.csv', 'r') as file:
reader = csv.reader(file)
admissionNums = {x[0] for x in reader if x}
student_data = []
for field in student_fields:
print(field)
value = input("Enter " + field + ": ")
# while the user is entering the admission no. field and they are entering a duplicate, keep prompting them for a new/unique number
while field == 'Admission no.' and value in admissionNums:
print("Admission no. already in file, try again")
value = input("Enter " + field + ": ")
student_data.append(value)
# I also added `newline=''` so that it would stop creating an empty row when writing to the file
# You can remove this if you want to keep making a new row every time you write to it
with open(student_database,"a",encoding = "utf-8", newline='') as f:
writer = csv.writer(f)
writer.writerows([student_data])
print("Data saved successfully")
input("Press any key to continue")
# The return statement here is not necessary
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
In response to the previous question, I am now trying to do something different. I am trying to write the user's name and their score to a text file that I called, just for testing purposes (newfile.txt):
This is the code so far:
file = open("newfile.txt", "w")
user_name = str(input("What is your name?"))
user_score = int(input("What score did you get?"))
file.write(user_name, ":", user_score "\n")
I am trying to write the name and the score in the form name:score, so for instance since my name is Taylor and if I got a score of 10, I would expect the file to show Taylor : 10.
Why is this not working?
.write() takes a single argument. You need to create a single string to pass. Instead of
file.write(user_name, ":", user_score "\n")
You could use str.format() to create your string.
file.write('{} : {}\n'.format(user_name, user_score))
As a side note, I would recommend using the with keyword to handle file opening and closing for you.
with open("newfile.txt", "w") as f:
user_name = str(input("What is your name? "))
user_score = int(input("What score did you get? "))
f.write('{} : {}\n'.format(user_name, user_score))
How about put the content you want to write to the file in a new var? And write() only take a parameter of string type but user_score is an int type:
file = open("newfile.txt", "w")
user_name = str(input("What is your name?"))
user_score = int(input("What score did you get?"))
content = user_name + ':' + str(user_score) + '\n'
file.write(content)
file.close() # close the file
Besides, make sure close the file or it will not close until your program ends.
I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)
So I have a question that requires this The features : color,size,flesh and class are separated by spaces. Write a Python program that asks the user for the names of the input file (in this case animals.txt) and the output file (any name). The program reads in the lines of the input file, ignores comment lines (lines starting with #) and blank lines and computes and prints the answers to the following questions:
Total number of animals?
Total number of dangerous animals?
Number of large animals that are safe?
Number of animals that are brown and dangerous?
Number of safe animals with red color or hard flesh?
So I finished the program and everything seems to be working but so far when I enter the code and initiate the program, everything works, no errors, nothing but no output file gets generated. I don't know what is wrong exactly but if someone could point me in the right direction it would be highly appreciated.
import os.path
endofprogram = False
try:
filename1 = input("Enter the name of input file: ")
filename2 = input("Enter the name of output file: ")
while os.path.isfile(filename2):
filename2 = input("File Exists! Enter new name for output file: ")
infile = open(filename1, 'r')
ofile = open(filename2, "w")
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
alist = []
blist = []
clist = []
largesafe = 0
dangerous = 0
browndangerous = 0
redhard = 0
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
colour, size, flesh, clas = line.split('\t')
alist = alist.append(colour)
animals = alist.count()
while clas == "dangerous":
dangerous = dangerous + 1
while size == "large" and clas == "safe":
largesafe = largesafe + 1
while colour == "brown" and clas == "dangerous":
browndangerous = browndangerous + 1
while colour == "red" and flesh == "hard":
redhard = redhard + 1
ofile.write(print("Animals = \n", animals))
ofile.write(print("Dangerous = \n", dangerous))
ofile.write(print("Brown and dangerous = \n", browndangerous))
ofile.write(print("Large and safe = \n", largesafe))
ofile.write(print("Safe and red color or hard flesh= \n", redhard))
infile.close()
ofile.close()
Your indentation has completely messed the program up. The biggest offender is this section:
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
The if line will only ever be executed right after the endofprogram = True line, at which point endofprogram == False will be false, and so nothing in the if block — which include the rest of the program — will be executed. You need to dedent everything from the if onwards by one level.
Maybe you can remove the print inside ofile.write
ofile.write(print("Animals = \n", animals))
to
ofile.write("Animals = \n" + str(animals))