Python writing to new lines - python-3.x

I'm trying to get this code to ask for the user's details then save them to a .txt file with commas separating the strings. I need to write to a new line every time I run the code but adding "/n" onto the end of the strings but it gives me all the user's data on the same line. any help?
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:"))
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+"/n")
print ("Your username is:",reg_user)
reg_write.close()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")

I think that you may want \n instead of /n. It is the actual newline character. Otherwise, it would be adding "/n" between each statement in the file. \n creates a newline.
print ("enter your name, age, and year group and password")
while True:
reg_name = input("Name:"))
reg_pass = input ("Password:")
reg_age = input ("age:")
reg_group = input ("Year Group")
print ("Is this infomation correct?")
print ("Name:",reg_name)
print ("password:",reg_pass)
print ("Age:",reg_age)
print ("Year Group:", reg_group)
reg_correct = input ("[Y/N]").lower()
if reg_correct == "y":
reg_user = reg_name[0:3]+reg_age
reg_write = open("D:\\Computer science\\Computing test\\logindata.txt","a")
reg_write.write (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group+"\n")
print ("Your username is:",reg_user) # ^^^
reg_write.close()
break
elif reg_correct == "n":
print ("Please Re-enter your infomation")
else:
Print ("Invalid input! Please try again...!")

Different way :
You can also avoid escape character by using writelines() method .
reg_write.writelines (reg_user+","+reg_name+","+reg_pass+","+reg_age+","+reg_group)

You can use the print function to write your information to a file. By using the pathlib module, you can easily run some error checking to help verify your file is accessible. With Python's recent addition of format strings, printing out variables can be very easy to accomplish.
#! /usr/bin/env python3
import pathlib
def main():
while True:
username = input('Username: ')
password = input('Password: ')
year_age = input('Age: ')
grouping = input('Group: ')
print('Is this information correct?')
print(f'Username: {username}\n'
f'Password: {password}\n'
f'Age: {year_age}\n'
f'Group: {grouping}')
# noinspection PyUnresolvedReferences
answer = input('Yes or no? ').casefold()
if 'yes'.startswith(answer):
path = pathlib.Path('login_data.csv')
if path.exists() and not path.is_file():
print('Your information cannot be saved.')
else:
with path.open('at') as file:
# noinspection PyTypeChecker
print(
username, password, year_age, grouping,
sep=',', file=file
)
break
elif 'no'.startswith(answer):
print('Please enter your information so that it is correct.')
else:
print('I did not understand your answer. Please try again.')
if __name__ == '__main__':
main()

Related

TypeError: method() takes 0 positional arguments but 1 was given

I wrote an input function python program,
But when run that code , IDE show that, "this function need to pass argument"
Even though ,I didn't declare any argument enter image description here
please help me how to solve this problem , Thank you in advance
list_number = list()
def input():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display +"#"
print(display)
display = ""
input()
diagram()
Several errors are noticed at glance:
mixture of namespace
You declared list_number as a global variable, but you cannot set value to it
directly insides a function. Instead, you can let the function return a value,
or use global statement to temporary allow a function to set a value to
a global variable temperary.
Read more on offical document, or search keyword python namespace for
relative articles.
name collision on builtin keyword
Some special word are reserved by python and could not be used as variable or
function name, input is amoung them.
BTW: The title of your question and example code layout is confusion! Follow the
tour to learn how to ask a better question and improve layout, so that people
can help you out.
Example code: though the test part has some bug I don't solved...
# remove: move it to a main progress for future design
# list_number = list()
# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
if pargs:
for arg in pargs:
try:
yield int(arg)
except ValueError:
pass
else:
count = 0
while True:
# move out of `try` statement as it won't raise any exceptions
# imply lowercase for easier string comparison
userinput = input("Enter your number in to list: ").lower()
if userinput in ['quit', 'q']:
# for interactive, give user a response
print("Quit input procedure. Preparing Diagram...")
break
try:
number = int(userinput)
except ValueError:
# raise a error and the output will print to output by default
# there is no need to `print` an error
# and, for improve, you can raise a more specific message
# and continue your program
msg = "The program wants a number as input, please try again.\n"
msg += "Type `Quit` to exit input procedure."
print(msg)
continue
except KeyboardInterrupt:
msg = "You pressed Interrupt Keystroke, program exit."
print(msg)
return 0
# print a message and pass the value intercepted
count += 1
print("%d: number %d is added to queue." % (count, number))
yield number
def diagram(numbers):
# there is no need to iter a list by index
# and I am **not** sure what you want from your origin code
# if what you wnat is:
# join number with "#" sign
# then just use the builtins str.join method
# valid: is_list_like
if is_list_like(numbers):
numstr = map(str, numbers)
ret = "#".join(numstr)
else:
ret = "Nothing to export."
return ret
def is_list_like(obj):
"""fork from pandas.api.types.is_list_like,
search c_is_list_like as keyword"""
return (
# equiv: `isinstance(obj, abc.Iterable)`
hasattr(obj, "__iter__") and not isinstance(obj, type)
# we do not count strings/unicode/bytes as list-like
and not isinstance(obj, (str, bytes))
)
def main(*pargs):
# get a generator of user input
# if passed in values, accept parameter as user input for test
msgout = ""
if pargs:
# bug: test input not filtered by int() function
list_number = list(myinput(pargs))
print("Run builtin test module.")
else:
list_number = list(myinput())
count = len(list_number)
# process your input by whatever means you need
if count == 1:
msgout += "Received %d number from user input.\n" % count
else:
msgout += "Received %d numbers from user input.\n" % count
msgout += "The diagram is:\n%s" % diagram(list_number)
print(msgout)
def test():
"""simulate user input"""
userinputs = [
['a', 1, 5, 4, 9, 'q'],
[999, 'Quit'],
['q'],
]
for userinput in userinputs:
main(*userinput)
# test bug:
# 1. charactor is printed as output, too
if __name__ == "__main__":
# remove test() if you don't need it
test()
main()
Well I would change your function name from input to something else because you cannot have any function named anything from base python named in your function, This is probably the reason for your error.
Like the others said, input() is a builtin function in Python. Try this following code:
list_number = list()
def input_func():
while True:
try:
number = input("Enter your number in to list = ")
if number == "Quit":
break
number = int(number)
list_number.append(number)
print(list_number)
except ValueError as e:
print(e)
def diagram():
display = ""
for i in list_number:
for j in range(i):
display = display + "#"
print(display)
display = ""
input_func()
diagram()
Also, nice to note that try should be used more precisely only where the exception is expected to be thrown. You could rewrite input_func with that in mind, such as:
def input_func():
while True:
number = input("Enter your number in to list = ")
if number == "Quit":
break
try:
number = int(number)
except ValueError as e:
print(e)
else:
list_number.append(number)
print(list_number)

How to store multiple lines in a file with python?

How to write to a file in python3 in such a way that your new input gets stored in the same file but on a new line and if you use append mode it writes this new input without spaces.
def register():
with open('username.txt', mode='a')as user_file:
username = input('Enter Username : ')
user_file.write(f"{username}\n")
with open('password.txt', mode='a')as pass_file:
password = input('Enter Password: ')
pass_file.write(f'{password}\n')
def login() :
with open('username.txt', mode='r')as user_file:
validate_u = user_file.readlines()
with open('password.txt', mode='r')as pass_file:
validate_p = pass_file.readlines()
l_user = input('Username: ')
l_pass = input('Password: ')
if l_user == validate_u and l_pass == validate_p:
print('Login successful')
else:
print('login failed')
import Enigma_Register
import Enigma_login
print('1-Login\n2-Register')
choice = int(input("enter choice: "))
if choice == 1:
Enigma_login.login()
elif choice == 2:
Enigma_Register.register()
Enigma_login.login()
else:
print('Invalid Choice!')
You can try to write to a file appending the spaces or putting line endings in write.
Here is an example with line endings:
myinput = input('input number: ')
with open('data.txt', 'a') as f:
f.write('{}\n'.format(myinput))
You can do this by adding /n at the last.
Such as
f.write( "I am a boy /n")
f.write("I am a student /n")

comparing user input with a list of strings

I am attempting to prompt the user to type four full names that exist in a text file, then compare the user input with the list of full names to see if they exist and display what the user inputted in the order entered. Every time I run this code the error keeps saying object is not subscriptable.
What's going wrong?
class Voting:
def __init__(self):
with open("PresidentCandidates.txt", 'r') as file:
lines = file.readlines()
self.Candidates = set([s.strip() for s in lines])
print(self.Candidates)
def presidentvoting(self):
userinput = input("Enter 4 names in the order of preference, who you will like to be president ")
userInput = list[userinput]
if userInput in self.Candidates:
print(userinput)
else:
print("fail")
In the line:
userInput = list[userinput]
you need to use normal brackets rather than square brackets. i.e.
userInput = list(userinput)
This should fix the error. However you have another bug in your code. To fix this, change:
userInput = list(userinput)
if userInput in self.Candidates:
print(userinput)
else:
print("fail")
to
userInput = userinput.split(' ')
for i in userInput
if i in self.Candidates:
print(userinput)
else:
print("fail")
This is because, you need to check each item in the userInput list against your text file list, rather than comparing the whole userInput list against your text file list.
This code fix assumes that your input is separated with spaces.
e.g. "President1 President2 President3 President4"
If you are using another separator, edit:
userInput = userinput.split(' ')
to
userInput = userinput.split(<INSERT SEPARATOR HERE>)
EDIT: 25/01/20 [REQUESTED NOT TO PRINT USERINPUT 4 TIMES]
change:
userInput = userinput.split(' ')
for i in userInput
if i in self.Candidates:
print(userinput)
else:
print("fail")
to
userInput = userinput.split(' ')
for i in userInput
if not (i in self.Candidates):
print("fail")
return
print(userinput)

How to fix "IndexError: list index out of range" in Python?

I am trying to write a quiz program that saves and reads from text files, storing the users details in a unique text file for each user. Each user file is saved in the format:
name, age, (line 1)
username (line 2)
password (line 3)
I currently am getting the error 'IndexError: list index out of range' whilst attempting to read a two lines from a file so the program can decide whether the user has entered the correct login details. I understand that the error is due to the program not seeing line three but I cannot understand why.
import sys
def signUp ():
name=input("Please enter your first name and last name. \n- ")
name = name.lower()
username=name[0:3]
age= input("Please input your age. \n- ")
username = username + age
password = input("Please input a password. \n- ")
print ("Your username is "+username+" and your password is " +password)
userfile = open(name+".txt", "r")
userfile.write(name+", "+age+"\n")
userfile.write(username+"\n")
userfile.write(password+"\n")
userfile.close()
return name, age, username, password
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
loginFile = open (logname+".txt", "r")
inputuname = input ("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
username = loginFile.readlines(1)
password = loginFile.readlines(2)
print (username)
print (password)
loginFile.close()
if inputuname == username[1].strip("\n") and inputpword ==
password[2].strip("\n"):
print("success")
quiz()
else:
print("invalid")
def main():
valid = False
print ("1. Login")
print ("2. Create Account")
print ("3. Exit Program")
while valid != True:
choice =input("Enter an Option: ")
if choice == "1":
login()
elif choice == ("2"):
user = signUp()
elif choice== ("3"):
valid = True
else:
print("not a valid option")
def quiz():
score = 0
topic = input ("Please choose the topic for the quiz. The topics available
are: \n- Computer Science \n- History")
difficulty = input("Please choose the diffilculty. The difficulties
available are: \n- Easy \n- Medium \n- Hard")
questions = open(topic+"questions.txt", "r")
for i in range(0,4):
questions = open(topic+" "+difficulty+".txt", "r")
question = questions.readline(i)
print(question)
answers = open (topic+" "+difficulty+" answers.txt", "r")
answer = answers.readline(i)
print(answer)
userAns = input()
questions.close
answers.close
if userAns == answer:
score = score + 1
return score
main()
You should use with open(....) as name: for file operations.
When writing to a file you should use a for append / r+ for read+write, or w to recreate it - not 'r' that is for reading only.
As for your login():
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
inputuname = input("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
with open(logname + ".txt", "r") as loginFile:
loginfile.readline() # skip name + age line
username = loginFile.readline() # read a single line
password = loginFile.readline() # read a single line
print(username)
print(password)
if inputuname == username.strip("\n") and inputpword == password.strip("\n"):
print("success")
quiz()
else:
print("invalid")
File-Doku: reading-and-writing-files
If the file does not exist your code will crash, see How do I check whether a file exists using Python?

Ignoring quotes while sorting lists in Python?

I am making a program to read from a file, alphabetize the info, and paste it into an output.. The only issue I am having is in the information that begins with quotes ("").
The main function for the program is to auto-sort MLA works cited pages (for fun obviously).
Here is the code... I would love any criticism, suggestions, opinions (Please keep in mind this is my first functioning program)
TL;DR -- How to ignore " 's and still alphabetize the data based on the next characters..
Code:
import os, sys
#List for text
mainlist = []
manlist = []
#Definitions
def fileread():
with open("input.txt", "r+") as f:
for newline in f:
str = newline.replace('\n', '')
#print(str)
manlist.append(str)
mansort(manlist)
#print("Debug")
#print(manlist)
def main():
print("Input Data(Type 'Done' When Complete or Type 'Manual' For file-read):")
x = input()
if x.lower() == 'done':
sort(mainlist)
elif x == '':
print("You must type something!")
main()
elif x.lower() == 'manual':
fileread()
else:
mainlist.append(x)
main()
def mansort(manlist):
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
manlist = sorted(manlist, key=str.lower)
for s in manlist:
finalstring2 = '\n'.join(str(manlist) for manlist in manlist)
if filename == '':
print("You must choose a name!")
elif filename.lower() == 'exit':
sys.exit()
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring2))
def sort(mainlist):
os.system("cls")
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
if filename.lower() == 'exit':
sys.exit()
elif filename == '':
print("You must type something!")
sort(mainlist)
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
Please keep all criticism constructive... Also, just as an example, I want "beta" to come after alpha, but with my current program, it will come first due to "" 's
sorted(mainlist, key=str.lower)
You've already figured out that you can perform some transformation on each item on mainlist, and sort by that "mapped" value. This technique is sometimes known as a Schwartzian Transform.
Just go one step further - remove the quotes and convert it to lower case.
sorted(mainlist, key=lambda s: s.strip('"').lower())

Resources