So I have this program that I've written in Python 2.7 which takes user input of various employee information and writes it to a file. I put the main block of code into a function, because I want to be able to run it multiple times. The code I currently have is below:
def employeeInformation():
# opens text file data will be stored in
with open('employeeFile.txt', 'w') as dataFile:
# gets user input for employee name
employeeName = raw_input('Employee Name: ')
# checks if the input is a string or not
if not employeeName.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeName + '\n')
# gets user input for employee age
employeeAge = raw_input('Employee Age: ')
if not employeeAge.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeAge + '\n')
# gets user input for employee role
employeeRole = raw_input('Employee Role: ')
if not employeeRole.isalpha():
print('Invalid data entry')
else:
# if input is string, write data to file
dataFile.write(employeeRole + '\n')
employeeSalary = raw_input('Employee Salary: ')
if not employeeSalary.isdigit():
print('Invalid data entry')
else:
# if input is number, write data to file
dataFile.write(employeeSalary + '\n')
dataFile.close()
employeeInformation()
employeeInformation()
employeeInformation()
Whenever it runs however, it only saves on of the function runs in the file, so instead of there being 9 pieces of data in the text file, there are only 3, which are the last 3 I input into the program. I can't figure out why it seems to be overwriting the data each time the function runs, does anyone know whats wrong with this code?
your problem is you are using the 'w' mode of an openfile.
just as you can open in mode 'r' for reading a file, you can use 'a' for appending to a file.
just change this line:
with open('employeeFile.txt', 'w') as dataFile:
to
with open('employeeFile.txt', 'a') as dataFile:
that should solve your problems!
Related
I have the following task:
We will write a program called student_register.py that allows students to register for an exam venue.
First, ask the user how many students are registering.
Create a for loop that runs for that amount of students
Each loop asks for the student to enter their ID number.
Write each of the ID numbers to a Text File called reg_form.txt
This will be used as an attendance register that they will sign when they arrive at the exam venue.
I think the following code I have is close as it saves the text file but only saves the first inputted ID number and does not display the others.
students = int(input("Please enter the amount of students registered."))
id_number = ""
for a in range (0, students):
id_number = (int(input("Please enter student ID numbers.")))
id_number = id_number + 1
reg_form = open('reg_form.txt', 'w')
reg_form.write("Student ID numbers: \n" + str(id_number))
print ("Thank you, ID numbers saved to txt file reg_form")
You are re-opening the file every loop, and you are opening it in write mode. This means you are overwriting any data in the file every loop.
A simple fix would be to open the file in append mode using 'a', alternatively you could store the results in a list and then write everything in one go at the end which would be nicer.
It's also good practise to close a file after you've finished with it, see Why Should I close files with Python. Whilst you can do this using reg_form.close() a better approach would be to use a context manager as this guarantees the file is always closed:
with open("reg_form.txt", "w") as my_file:
my_file.write("some data")
It is not saving because you are not closing the file stream.
I suggest that you use it with with keyword, it handles the opening and closing of your file and saving the data.
students = int(input("Please enter the amount of students registered."))
id_number = ""
for a in range (0, students):
id_number = (int(input("Please enter student ID numbers.")))
id_number = id_number + 1
with open('reg_form.txt', 'w') as file:
file.write("Student ID numbers: \n" + str(id_number))
print ("Thank you, ID numbers saved to txt file reg_form")
elif menuOption == "2":
with open("Hotel.txt", "a+") as file:
print (file.read())
Ive tried many different ways but my python file just refuses to print the txt contents. It is writing to the file but option 2 wont read it.
if menuOption == "1":
print("Please Type Your Guests Name.")
data1 = (input() + "\n")
for i in range (2,1000):
file = open("hotel.txt", "a")
file.write(data1)
print("Please Write your Guests Room")
data2 = (input("\n") + "\n")
file.write(data2)
data3 = random.randint(1, 999999)
file.write(str (data3))
print("Guest Added - Enjoy Your Stay.")
print("Guest Name is:", data1)
print("Guest Room Number Is:", data2)
print("Your Key Code Is:", data3)
I want all the above information to be added to a TXT. (That works) and then be able to read it also. which won't work.
Why and how can I fix?
You have to use r instead of a+ to read from file:
with open("Hotel.txt", "r") as file:
You are using a+ mode which is meant for appending to the file, you need to use r for reading.
Secondly I notice this
for i in range (2,1000):
file = open("hotel.txt", "a")
You are opening a new file handler for every iteration of the loop. Please open the file just once and then do whatever operations you need to like below.
with open("hotel.txt", "a") as fh:
do your processing here...
This has the added advantage automatically closing the file handler for you, otherwise you need to close the file handler yourself by using fh.close() which you are not doing in your code.
Also a slight variation to how you are using input, you don't need to print the message explicitly, you can do this with input like this.
name = input("Enter your name: ")
I used Python 3.6 version and now I want to save name & age at the file and then read the text as name + tab + age but I can't approach file read side.
My code:
while True:
print("-------------")
name=input("Name: ")
age=input ("Age: ")
contInput=input("Continue Input? (y/n) ")
fp.open("test.txt", "a")
fp.write(name+","+age+"\n")
if contInput=="n":
fp.close()
break
else:
continue
with open("test.txt", "r") as fp:
rd = fp.read().split('\n')
????
fp.close()
so I just confuse about file read. I want to print my saved data like below.
name [tab] age
but after used split method, rd type is list.
Can I divide name & age as each items?
fp.open("test.txt", "a")
At this point in your program, fp doesn't exist yet. Perhaps you meant fp = open(...) instead?
You're only closing the file if the user chose not to continue, but you're opening it every time through the loop. You should open and close it only once, or open and close it every time through the loop.
fp.write(name+","+"age"+"\n")
This writes the literal word age instead of the age variable. You probably wanted this instead: fp.write(name + "," + age + "\n")
Try this for your input loop:
with open("test.txt", "r") as fp:
for line in fp:
data = line.split(",")
name = data[0]
age = data[1]
I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below:
getUsrName = input("Enter username: ")
file = open("documents/pytho/login/cdat.txt", "r")
lines = file.readlines()
recievedUsrName = lines[1]
file.close()
print(getUsrName)
print(recievedUsrName)
if recievedUsrName == getUsrName:
print("hello")
elif getUsrName != recievedUsrName:
print("bye")
else:
Try it like:
if recievedUsrName.strip() == getUsrName:
...
It must be the trailing newline.
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!
Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'
f = open('test.txt', 'a')
Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"
f.write(sumOfStudent + "\n")