Cannot add record in new line in text file - python

I am trying to let the user add records to a text file that I have created. The record already has a few records added to it.
def add_new_employee():
with open("records.txt", "a") as storing_records:
storing_records.write(input("\n" + "please enter your details in the following format followed by commas between each field: User ID, Name, Age, Position, Salary, Years employed: "))
The problem is when I add a record for the first time it will work perfectly, the created record will be on a new line, but if I rerun the code and add in a new record then it will just join onto the end of the previous record and it will ignore the \n.

What if you would create a variable first and .write the input in a separate line?
I also added the line break after the input. It worked for me once like that.
def add_new_employee():
with open("records.txt", "a") as storing_records:
user_input = input("Please enter your details....")
storing_records.write(user_input + "\n")

Related

delete only 1 instance of a string from a file

I have a file that looks like this:
1234:AnneShirly:anneshirley#seneca.ca:4:5\[SRT111,OPS105,OPS110,SPR100,ENG100\]
3217:Illyas:illay#seneca.ca:2:4\[SRT211,OPS225,SPR200,ENG200\]
1127:john Marcus:johnmarcus#seneca.ca:1:4\[SRT111,OPS105,SPR100,ENG100\]
0001:Amin Malik:amin_malik#seneca.ca:1:3\[OPS105,SPR100,ENG100\]
I want to be able to ask the user for an input(the student number at the beginning of each line) and then ask which course they want to delete(the course codes are the list). So the program would delete the course from the list in the student number without deleting other instances of the course. Cause other students have the same courses.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if line.find(course) == -1:
file.write(line)
This just deletes the whole line but I only want to delete the course
Welcome to the site. You have a little ways to go to make this work. It would be good if you put some additional effort in to this before asking somebody to code this up. Let me suggest a structure for you that perhaps you can work on/augment and then you can re-post if you get stuck by editing your question above and/or commenting back on this answer. Here is a framework that I suggest:
make a section of code to read in your whole .dat file into memory. I would suggest putting the data into a dictionary that looks like this:
data = {1001: (name, email, <whatever the digits stand for>, [SRT111, OPS333, ...],
1044: ( ... )}
basically a dictionary with the ID as the key and the rest in a tuple or list. Test that, make sure it works OK by inspecting a few values.
Make a little "control loop" that uses your input statements, and see if you can locate the "record" from your dictionary. Add some "if" logic to do "something" if the ID is not found or if the user enters something like "quit" to exit/break the loop. Test it to make sure it can find the ID's and then test it again to see that it can find the course in the list inside the tuple/list with the data. You probably need another "if" statement in there to "do something" if the course is not in the data element. Test it.
Make a little "helper function" that can re-write a data element with the course removed. A suggested signature would be:
def remove_course(data_element, course):
# make the new data element (name, ... , [reduced course list]
return new_data_element
Test it, make sure it works.
Put those pieces together and you should have the ingredients to change the dictionary by using the loop and function to put the new data element into the dictionary, over-writing the old one.
Write a widget to write the new .dat file from the dictionary in its entirety.
EDIT:
You can make the dictionary from a data file with something like this:
filename = 'student_data.dat'
data = {} # an empty dictionary to stuff the results in
# use a context manager to handle opening/closing the file...
with open(filename, 'r') as src:
# loop through the lines
for line in src:
# strip any whitespace from the end and tokenize the line by ":"
tokens = line.strip().split(':')
# check it... (remove later)
print(tokens)
# gather the pieces, make conversions as necessary...
stu_id = int(tokens[0])
name = tokens[1]
email = tokens[2]
some_number = int(tokens[3])
# splitting the number from the list of courses is a little complicated
# you *could* do this more elegantly with regex, but for your level,
# here is a simple way to find the "chop points" and split this up...
last_blobs = tokens[4].split('[')
course_count = int(last_blobs[0])
course_list = last_blobs[1][:-1] # everything except the last bracket
# split up the courses by comma
courses = course_list.split(',')
# now stuff that into the dictionary...
# a little sanity check:
if data.get(stu_id):
print(f'duplicate ID found: {stu_id}. OVERWRITING')
data[stu_id] = (name,
email,
some_number,
course_count,
courses)
for key, value in data.items():
print(key, value)
i got something for you. What you want to do is to find the student first and then delete the course: like this.
studentid = input("enter studentid")
course = input("enter the course to delete")
with open("studentDatabase.dat") as file:
f = file.readlines()
with open("studentDatabase.dat","w") as file:
for line in lines:
if studentid in line: # Check if it's the right sudent
line = line.replace(course, "") # replace course with nothing
file.write(line)
You want to check if we are looking at the correct student, then replace the line but without the course code. Hope you can find it useful.

Python using while loop with reading from a file with if statement

please can you tell me what is wrong with my code?
I have been trying to make this work it's not happening.
In python, I created a function that I want to search for students by their ID,
I need to make it specific and if it's not int like (str) I want it to show an error message.
I used while true, but it's not working, as it goes to the end of the function without checking the if condition.
Here is the code:
#open the file as student file (variable)
with open("studentfile.txt","r") as studentfile:
#call upon our reader (this allows us to work with our file)
studentfileReader=csv.reader(studentfile)
while True:
try:
idnumber=int(input("Please enter student ID :"))
break
except ValueError:
print("Invalid Input")
#for each row that is read by the Reader
for row in studentfileReader:
#and for each field in that row (this does it automatically for us)
for field in row:
#if the field is equal to the id number that is being searched for
if field ==idnumber:
#print the row corresponding to that ID number
print(row)
#Return to main menu for further options or to quit the program
menu()
Maybe there are other ways,
but if I put if statement without while true,
it's not going to show error message for the user inside the program

Need multiple inputs saved to another single input, all information given by user

Building a webscraper for a game I love and right now came into a little issue with python, what I want to do could best be show as:
userdata = { ' ', [ ]}
I'm new to writing python so my question is would this work given the following scenario:
User's account name (which players in the game use to message each other) wants to attach multiple character names to that single account name so other players know that all these characters belong to that one account.
The end result should be something like this:
"Please enter your account name followed by which characters you wish associated with this account:"
user input: Leafzer Leaf1 Leaf2 Leaf3
current limitations in the game work to python's advantage as account and character names can not have any white space. I was considering using split such as:
x = [str(x) for x in input("Enter user data: ").split()]
but as it stands neither of these seem to work quite right.
To reiterate and maybe clear some of the confusion: Writing a website scraper that allows players in the game to enter their account name and a list of mules (characters in the game that just hold items). The list of mules and the account name must be separate as my scraper uses the list of mules to go to a certain website using that mule name and downloads the data into a searchable csv file. If another player searches for an item that is within that csv file, it brings up the account name associated with the mule rather than the mule name and displays the account name to player searching for the item.
I'm stuck trying to figure out how to obtain the user data in this manner. Any help would be appreciated.
Are you after something like this:
users = {}
user, *chars = input("Please input your name and characters: ").split(" ")
users[user] = chars
?
Or slightly less confusingly (but not nearly as neatly):
users = {}
words = input("Please input your name and characters: ").split(" ")
user = words[0]
chars = words[1:]
users[user] = chars
But * unpacking is great, and everyone should use it!
P.S. for your second use case, just call input() twice!:
username = input("Please input your name: ")
chars = input("Please input your characters: ").split(" ")

Reading list from text file and converting it to string

Hello, I recently started to learn Python, so that's my best explain to you, cause my English skills are not Perfectly.
I made a script which is reading a list from text file, and then my problem is converting it to string, so I could display it in the print function. After doing that, when user is typing his "Nickname", lets say. The script is already readen the list from text file. Also the i don't know if used the split(',') Function, that should split the words with those , from the words in the text file used for list. Here are some pictures of my code.
https://gyazo.com/db797ca0998286248bf846ac70c94067 (Main code)
https://gyazo.com/918aaba9b749116d842fccb78f6204a8 (Text file - list of usernames which are "BANNED")
The text code file name is Listas_BAN.txt.
I've tried to do all this thing myself, i did some research before posting this, but many methods are outdated.
# Name
name = input("~ Please enter Your name below\n")
print("Welcome " + str(name))
def clear(): return os.system('cls')
clear() # Clearina viska.
# define empty list
Ban_Listo_Read = open('Listas_BAN.txt', mode='r')
Ban_Listo_Read = Ban_Listo_Read.readlines()
Ban = Ban_Listo_Read.list(ban)
# Print the function (LIST) in string .
print("Your'e Banned. You'r nickname is - ", + Ban_Listo_Read).Select (' %s ', %s str(name)) # Select the User nickname from
# The input which he typed. (Check for BAN, In the List.)
# Text file is the List Location . - Listas_BAN.txt
enter image description here
enter image description here
I'm getting Wrong Syntax Error
ll = open('untitled.txt', mode='r').readlines()
print("".join(ll).replace('\n', '.'))
name = input("~ Please enter Your name below\n")
if name in ll:
print('your name {n} is in the list'.format(n=name))
EDIT:
plus, you shall consider using string formatting:
var1 = ...
var2 = ...
print("{x}...{y}".format(x=var1, y=var2)
or python 3.7
print(f"{var1}...{var2}")
EDIT:
f.readlines()
https://docs.python.org/3.7/tutorial/inputoutput.html
If you want to read all the lines of a file in a list you can also use
list(f) or f.readlines().

How would I save the data to a .csv file

I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :
import time
import math
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
UserName = input("What is your name?:")#Ask the user for there name.
if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
continue#Continues with the code when correct input given.
else:#It breaks out of the while loop and proceeds with the quiz
break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
if ClassSelection=="1":
ClassChosen=1
elif ClassSelection=="2":
ClassChosen=1
elif ClassSelection=="3":
ClassChosen=1
else:
print("You must write 1, 2, or 3.")
ClassSelection=input("Enter the class you are in")
print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between
print (3 - i)#counts down by one
time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
score=0#No questions have been answered correctly yet so score is set to zero
for questionNum in range(10):#I have used this to allow me to set my Parameters.
Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.
UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
score = score + 1#If the user gets the question right 1 should be added to the score.
print("You are correct! :D")#The program will congratulate the user.
print("_______________________________________________")
else:#If the users answer is not the same as the real answer then it will print a wrong message.
print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
print("The answer was", RealAnswer)
print("________________________________________________")#This will be used to split the quiz.
print()#This is used to format the quiz.
print("__________________________________________________")
print("Thank you for completing the quiz!")
print("Your Score is loading")
import time
time.sleep(2)
print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
print()#This is used to format the code
del RecentStudent[0]
RecentStudent.append(score)
print("Your three most recent scores are:",RecentStudent)
print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
#It tells the user that they are finished
def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
print("Quiz Finished")#It tells the user that they are finished
MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class1Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class1))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
Class2=[]#classA list is created and is empty.
Class2.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class2.append(UserName)#The name variable is appended as the second item.
Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class2.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class2Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class2))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
elif ClassSelection==3:
Class3 = []#classA list is created and is empty.
Class3.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class3.append(UserName)#The name variable is appended as the second item.
Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class3.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class3))#Allows me to write the class3 list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .
I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):
import csv
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
with open('Class1Scores.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerow(str(Class1))
writer.writerow("\n")
Gentle into to the csv module
Because we're using the with keyword, there is no need to call file.close()
For a more advanced way of doing this, you could use pandas to_csv
Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)). But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html

Categories