I fixed most of my code but the only problem I'm having is that none of the text is showing. I'm supposed to input golfer names and their scores but nothing shows up when I run the program.
def main():
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('playerData.txt', 'w')
while counter < numPlayers:
name = raw_input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()
I have slightly modified this script to try it here and it actually worked:
It prompts the players' names and scores by players number.
It saves the players file
It reads the players file and show scoring results.
I had to change raw_input to input as for Python3 and called the w function passing a number of player by user inputs:
def main():
num_players = input("How many players?")
w( int(num_players) )
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('golfers.txt', 'w')
while counter < numPlayers:
name = input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()
Related
I came across a project geared toward starters like myself - creating a CLI passwordcreator.
I have with the help of a few guides completed the generator and added a few of my own features, however there is one feature I can't seem to figure out how to implement; saving the output to a file.
In the terminal the passwords shows up perfectly fine line by line, however if I try to save the output to a file it only saves the last password, and it seperates each letter by line.
My code is below, together with examples of output from both the terminal and a .txt file.
import string
import random
from os import system, name
letters = list(string.ascii_letters)
digits = list(string.digits)
special_characters = list("!##$%^&*()£")
characters = list(string.ascii_letters + string.digits + '!##$%^&*()£')
def clear():
if name == 'nt':
_ = system('CLS')
else:
_ = system('clear')
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input('Enter amount of passwords: '))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length -1:
print("Characters total count is greater than desired password length")
exit()
clear()
password = []
print("Following passwords saved to Passwords.txt, please move the file before generating new passords, as a new generation will overwrite existing")
print('\n')
for pwd in range(amount):
password = []
for c in range(digits_count):
password.append(random.choice(digits))
for c in range(letters_count):
password.append(random.choice(letters))
for c in range(special_characters_count):
password.append(random.choice(special_characters))
if character_count < length:
random.shuffle(characters)
for c in range(length - character_count):
password.append(random.choice(characters))
random.shuffle(password)
if str(password) < str(length):
return()
else:
print("".join(password))
with open('Passowrds.txt', 'w') as file:
for line in ("".join(password)):
file.write(line)
file.write('\n')
#file = open('Passwords.txt', 'w')
#str1 = repr(password)
#file.write('\n' + str1 + '\n')
#file.close
#f = open('Passwords.txt', 'r')
#if f .mode == 'r':
# contents=f.read
generate_random_password()
This is what the output from the terminal looks like:
Following passwords saved to Passwords.txt, please move the file
before generating new passords, as a new generation will overwrite
existing
gtBVA3QDcUohDc£TfX(zVt*24
KD8PnMD£)25hvHh#3xj79$qZI
Dx^*2£srcLvRx5g3B3(nq0H&9
&r6^3MEsaV1RuDHzxq*(h3nO)
However what is saved in the .txt file looks like this:
&
r
6
^
3
M
E
s
a
V
1
R
u
D
H
z
x
q
*
(
h
3
n
O
)
The reason why your script is saving only 1 password is because you are opening the file to be written (which clears the contents of the file) for every password you are generating.
You want to do something along the lines of:
passwords = []
for _ in range(num_passwords):
password = ...
passwords.append(password)
with open("password.txt", "w") as f:
f.writelines(passwords)
Although there is nothing terrible about the way you're using the random library, I recommend taking a look at random.sample (without replacement) or random.choices (with replacement).
Also, using shuffling your characters list isn't adding additional randomness to your random.choice.
You don't have to convert the strings to lists in order to run choice:
>>> import random
>>> random.choice("abc")
'b'
A fuller example:
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input("Enter amount of passwords: "))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length - 1:
print("Characters total count is greater than desired password length")
exit()
clear()
passwords = []
for _ in range(amount):
chosen_digits = random.choices(digits, k=digits_count)
chosen_letters = random.choices(letters, k=letters_count)
chosen_special_characters = random.choices(
special_characters, k=special_characters_count
)
extra_characters_count = length - character_count
extra_characters = random.choices(characters, k=extra_characters_count)
password = (
chosen_digits
+ chosen_letters
+ chosen_special_characters
+ extra_characters
)
random.shuffle(password)
passwords.append("".join(password))
with open("Passwords.txt", "w") as f:
f.writelines(passwords)
I am working on some code for a homework assignment where I have to take the numbers in a the file, calculate the sum of them all, the average and how many lines there are. This is what I've come up with so far
invalidEntry= True
#Input validation
while (invalidEntry) :
try:
total = 0
lines = 0
Validate= input("Please enter the name of the text file. : ")
if Validate ==("Random.txt") :
red= open( 'Random.txt', 'r')
for count in red:
strip = line.strip("\n")
lines += 1
average = total/200
total = total + int(count)
print("The number of lines is : ",lines)
print ("The total sum is : " ,total)
print("The average is :" , average
invalidEntry= False
except:
print("This isn't a valid file!")
I keep getting a syntax error for the except function and I'm unsure if I have the input validation set up properly. Any help would be appreciated.
Try with:
except Exception as err:
Try this, fixed a few bugs for you:
import os
total = 0
lines = 0
# Input the file
IfValidate = False
while IfValidate == False:
validate = input("Please enter the name of the text file: ")
if os.path.isfile(validate) == True:
IfValidate = True
# Open the file
f = open(validate, 'r')
# Read every line and make it a list
f = f.readlines()
for line in f:
# Strip of \n
strip = line.strip("\n")
# Make the number a number
num = int(strip)
lines += 1
average = total / 200
total = total + int(num)
print("The number of lines is : ", lines)
print ("The total sum is : " , total)
print("The average is :" , average)
Is there an easier way to loop back the option to the main menu? How do i do it?
from collections import Counter
print (" M A I N - M E N U")
print ("1.People")
print ("2.Name")
print ("3. Country")
print ("4. Continent")
opt = int(input("Enter option: "))
if opt ==1:
print ("People")
from collections import Counter
counterY = Counter()
with open('json.txt') as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
people = int(splits[3])
counter1[name] += people
for name, pop_sum in counter1.most_common():
print(Name, ":", pop_sum)
elif opt == 2:
from collections import Counter
counterx = Counter()
with open("json.txt") as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
change = float(splits[6])
country = splits[1].strip()
counter2[country] += change
#Percentage Change By Countries"
print()
print ("Countries"):
print(country)
Is there an easier way to loop back the option to the main menu? How do i do it?
Welcome to StackOverflow!
Just wrap around your code in a while(True) and if one option matches the 4, it will end the program, otherwise it will print the main menu again.
PS: I got your main menu in a function so that your code could be more readable.
import turtle
from collections import Counter
def main_menu():
print(30 * '-')
print(" M A I N - M E N U")
print(30 * '-')
print("1.Total Populations of the different continents & Continent with the lowest Population")
print("2.Percentage Change(%) for different countries")
print("3. Choose a country")
print("4. Exit")
print(30 * '-')
while(True):
main_menu()
opt = int(input("Enter option: "))
if opt ==1:
print("Continents Sorted By Population")
from collections import Counter
counter1 = Counter()
with open('demo.txt') as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
population = int(splits[3])
continent = splits[-1].strip()
counter1[continent] += population
# Print continents sorted by population
for continent, pop_sum in counter1.most_common():
print(continent, ":", pop_sum)
#Finding continent with lowest population
counter3 = Counter()
with open("demo.txt") as f:
for i in range(0,2):
next(f)
for line in f:
counter3[continent] += population
for continent, pop_total in counter3.most_common():
print()
print("Continent with the Lowest Population")
print(continent,":", pop_sum)
print()
elif opt == 2:
from collections import Counter
counter2 = Counter()
with open("demo.txt") as f:
for i in range(0,2):
next(f)
for line in f:
splits = line.split(';')
change = float(splits[6])
country = splits[1].strip()
counter2[country] += change
#Percentage Change By Countries"
print()
print("Percentage Change By Countries")
for country, change_sum in counter2.most_common():
print(country, change_sum,"%")
elif opt == 4:
break
def file_search():
userInput = input('Enter a country: ').lower()
result = []
with open("demo.txt", 'r') as f:
for x in f:
if userInput in x.lower():
result.append(x.split(';'))
for s in result:
print(s[1] + " \nCountry Rank: "+ s[0]+ " \n2019 population: " + s[3] + "\nPopulation change(%)"+s[6]+"\nContinent: "+ s[7])
file_search()
This is meant to ask a user for their username, find the username in a textfile and then output in columns, just their information. The information is ID, Last name, Year joined, Status, Nights booked and Points. How do I do this???
import time
membr = int(input("Do you have a membership already?\n"
"1.Yes\n"
"2.No\n"
"Option: "))
if membr == 1:
MemberID = []
LastName = []
YearJoined = []
Status = []
NightsBooked = []
Points = []
theirid = input("Please enter your id number (It is case sensitive): ")
Myfile = open("Memberships.txt", "r")
x = 0
for line in Myfile:
if theirid in line: return(line)
information = line.split(",")
MemberID.append(information[0])
LastName.append(information[1])
YearJoined.append(information[2])
Status.append(information[3])
NightsBooked.append(information[4])
Points.append(information[5])
x = x+1
Myfile.close()
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
for y in range(1,x):
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
time.sleep(2)
mainmenu()
elif membr == 2:
createnewuser()
else:
print("Invalid")
time.sleep(2)
mainmenu()
You don't need to return the line there.
...
YearJoined = []
Status = []
NightsBooked = []
Points = []
theirid = input("Please enter your id number (It is case sensitive): ")
Myfile = open("Memberships.txt", "r")
x = 0
for line in Myfile:
# this will use the line found to do your work.
if theirid in line:
information = line.split(",")
MemberID.append(information[0])
LastName.append(information[1])
YearJoined.append(information[2])
Status.append(information[3])
NightsBooked.append(information[4])
Points.append(information[5])
x = x+1
Myfile.close()
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
for y in range(1,x):
print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
time.sleep(2)
mainmenu()
elif membr == 2:
createnewuser()
else:
print("Invalid")
time.sleep(2)
mainmenu()
def open_file():
data=open("data_full.txt")
return data
def process_file(data):
out_file = input("Enter a name for the output file: ")
output_file= open(out_file, "w")
user_year = int(input("Enter a year: "))
user_int_count= int(input("Enter a integer count: "))
cnt = 0
data.readline()
for line in data:
cnt+= 1
field = line.strip().split()
line_list = [int(n) for n in field]
total = sum(line_list[1:])
year = line_list[0]
avg = int(round((total/12),0))
if user_year == year:
output_file.write("{:<d} {:<d}".format(year, avg))
print()
print( "{:<d} {:<d}".format(year, avg))
output_file.close()
def main():
while True:
try:
f=open_file()
break
except FileNotFoundError:
print("Invalid file name. Try Again.")
process_file(f)
f.close()
main()
this should print a range from the year entered through the incremented value assuming that's what your asking. If not please rephrase your question as it is a bit hard to interpret.
for x in range(user_year, user_year + count):
print x
I'm basing this answer on a more literal interpretation of the question.
def year_range(year_date, number_of_years): #assuming these are of type int.
output = '{}-{}'.format(year_date, year_date+number_of_years)
print(output)
so year_range(2000, 5)
gives you "2000-2005"