How to store multiple lines in a file with python? - python-3.x

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")

Related

A permanent list change(Save python file)

I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed

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?

Python writing to new lines

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()

How to delete a specific line in a text file using user input Python 3

I have a problem with a python 3 program. I am trying to build a function that delets a specific line in a text file using user input but can't for the life of me get it to work. Since I am a beginner i was wondering if someone more expicienced could help me with buildning the function.
Python 3 code:
def main():
players = load_results_from_file("user_res.txt")
while True:
show_menu()
user_choice = input("Välj alternativ: ")
print()
if user_choice == "1":
show_players(players)
elif user_choice == "2":
add_player(players)
elif user_choice == "3":
save_players(players, "user_res.txt")
elif user_choice == "4":
del_player(players)
elif user_choice == "5":
break
else:
print("Du angav ett felaktivt val, försök igen")
print("Ha en bra dag!")
def save_players(players, file_name):
my_file = open(file_name, "w")
for player in players:
my_file.write("{};{};{};{}\n".format(player["name"],
player["round_1"],
player["round_2"], player["round_3"]))
my_file.close()
print("Sparat!")
def add_player(players):
name = input("Ange namn: ")
round_1 = input("Ange varv 1: ")
round_2 = input("Ange varv 2: ")
round_3 = input("Ange varv 3: ")
players.append({
"name": name,
"round_1": round_1,
"round_2": round_2,
"round_3": round_3
})
def show_players(players):
print("*"*40)
print("Mini Golf")
print("*"*40)
for player in players:
print("{:15} {} {} {}".format(player["name"], player["round_1"],
player["round_2"], player["round_3"]))
print()
def show_menu():
print("Klubbmästerskap i minigolf")
print("*"*40)
print()
print("Meny")
print("*"*4)
print("1) Visa resultat")
print("2) Lägg till resultat")
print("3) Spara resultat")
print("4) Radera spelare")
print("5) Avsluta programmet")
def load_results_from_file(file_name):
players_list = []
try:
my_file = open(file_name, "r")
except:
my_file = open(file_name, "w").close()
print("INFO: Ingen fil hittades, så vi skapa den!")
return players_list
content = my_file.read()
for players in content.split("\n"):
try:
player = players.split(";")
players_list.append({
"name": player[0],
"round_1": player[1],
"round_2": player[1],
"round_3": player[1]
})
except:
pass
return players_list
def del_player(players):
delete_player = input("Ange spelaren du vill radera: ")
my_file = open("user_res.txt", "r")
lines = my_file.readlines()
my_file.close()
my_file = open("user_res.txt", "w")
for line in lines:
if delete_player not in lines:
my_file.write(line)
main()
Some of the text is in swedish and I will change that if it is necessary. But the function that I can't get to work is del_player. I want the user to input the player they want to delete with delete_player but so far it don't delete anything from the text file.
The problem is for sure a small TYPO marked in the source code with '#(1) !!!':
def del_player(players):
delete_player = input("Ange spelaren du vill radera: ")
my_file = open("user_res.txt", "r")
lines = my_file.readlines()
my_file.close()
my_file = open("user_res.txt", "w")
for line in lines:
print(type(delete_player), delete_player, type(line), line) #(2) !!!
if delete_player not in line: #(1) !!!
my_file.write(line)
If this doesn't solve the problem adding a print() (marked #(2) !!! as above can clarify how it comes that delete_player is not found in line.

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