I am new to programing and am having difficulties writing a program dealing with files. The program is to read a file, calculate an employees pay and an updated YTD pay total. After calculations the program will write to a new file.
This is what I have so far:
empName = ""
prevYTD = 0.0
payRate = 0.0
hoursWorked = 0.0
recordCount = 0
def startUp():
global empFile
print "\n\n" + "PAYROLL REPORT".center(110)+"\n"
print "Employee Name".ljust(30) + "Previous YTD".ljust(18) + \
"Updated YTD".ljust(18) + "Pay Rate".ljust(13) + \
"Hours Worked".ljust(19) + "Current Pay".ljust(8)
print "-"* 109
jobInfo = open("payroll_Assignment#7.txt", "r")
def readFile():
global empName, prevYTD, payRate, hoursWorked, eof
empRec = jobInfo.readline()
if empRec == "":
eof = True
else:
empName = empRec[:25]
prevYTD = float(empRec[25:40])
payRate = float(empRec[40:55])
hoursWorked = float(empRec[55:])
eof = False
def processRecords():
global recordCount
while not eof:
recordCount +=1
printRecord()
readFile()
def printRecord():
print empName, prevYTD, payRate, hoursWorked
def closeUp():
jobInfo.close()
print "\nNumber of records in the file was",recordCount
startUp()
readFile()
processRecords()
printRecord()
closeUp()
My problem is making a new file. The program is suppose to write to a new file and I don't know how to do it. Sorry for being so clumsy with this, I'm very new to it.
Not sure what the problem is but some idiom can make it easy for you.
You can avoid testing for EOF and the while loop.
File is iteratable hence you can iterate over it.
for line in open('myfile','r'):
doSomething(line)
See the details at : http://docs.python.org/tutorial/inputoutput.html
[Edit: Based on revised problem]
Opening a new file for writing should be easy in python
>>> logfile = open('test.log', 'w') # Opens a new file
>>> logfile = open('test.log', 'a') # Opens a existing file to append information
Look at the various modes of opening file in Python tutorial
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
http://docs.python.org/library/functions.html#open
Thank you for your answers. The program is to read a file, calculate employee pay and update the YTD total. After the calculations the program is to write a new file. I can not figure out how to do the calculations, make, write, or save the updated file.
Related
This question already has answers here:
Open file for reading and writing with truncate
(2 answers)
Closed 1 year ago.
I am trying to change some information in a textfile. Initially, the textfile looks like
Entertainment
70
Clothing
15
Food
25
after running this program
import os, sys
import cs50
from cs50 import get_int
def main():
print("Welcome to the money tracker program!")
SpentOnEntertainment = get_int("How much money do you plan on spending on Entertainment? ")
SpentOnClothing = get_int("How much money do you plan on spending on Clothing? ")
SpentOnFood = get_int("How much money do you plan on spending on Food? ")
Textfile = open("AFile2.txt", "r+")
currentfunds = Textfile.readlines()
if(SpentOnEntertainment > int(currentfunds[1])):
print("Sorry, you can only spend", currentfunds[1], "dollars on Entertainment.")
SpentOnEntertainment = int(currentfunds[1])
currentfunds[1] = str(int(currentfunds[1]) - SpentOnEntertainment) + "\n"
if(SpentOnClothing > int(currentfunds[3])):
print("Sorry, you can only spend", currentfunds[3], "dollars on Clothing.")
SpentOnClothing = int(currentfunds[3])
currentfunds[3] = str(int(currentfunds[3]) - SpentOnClothing) + "\n"
if(SpentOnFood > int(currentfunds[5])):
print("Sorry, you can only spend", currentfunds[5], "dollars on Food.")
SpentOnFood = int(currentfunds[5])
currentfunds[5] = str(int(currentfunds[5]) - SpentOnFood) + "\n"
Textfile.writelines(currentfunds)
sys.exit(0)
if(__name__ == "__main__"):
main()
which allows the user to choose how much money they want to spend and thus change the remaining money, the new lines are appended to the end of my original lines, and my end result (the text file) is
70
Clothing
15
Food
25Entertainment
25
Clothing
5
Food
0
How can I get rid of the first 6 lines as they are no longer relevant? I tried using methods such as deleting items [0:6] after rereading the list but nothing works.
The easiest way(that I can think is) to do is open the file
read the file and save the lines
and then empty the file
Textfile = open("AFile2.txt", "r+") # open file
currentfunds = list(Textfile.readlines()) #save the lines
Textfile.close() #close the file
open('AFile2.txt', 'w').close() #empty the file
Textfile = open("AFile2.txt", "r+") # re-open file
I have tried multiple ways to do this but I struggle. I am new to Python trying to learn currently.
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'w')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
This is the output
And this is what I get exported from this output
What I want to .txt export for example is.
John has ordered 1 times in total
Mike has ordered 1 times in total
etc
etc
Opening with a 'w' tag means you are opening the file in write mode. write mode overwrites the previously existing text if any or creates a new file if the file doesnt exist.So what you might wanna do is opening it in 'a' mode (append mode) so that it doesnt overwrite the file but just appends text to it
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + "
times in total\n")
your file permission should be append
w -
Opens in write-only mode. The pointer is placed at the beginning of
the file and this will overwrite any existing file with the same name.
It will create a new file if one with the same name doesn't exist
a -
Opens a file for appending new information to it. The pointer is
placed at the end of the file. A new file is created if one with the
same name doesn't exist. .
file1 = open('Orders_Per_Users.txt', 'a')
I hope you're enjoying your learning :)
problems are:
your code just update the text each time you add an item because of the mode of write/read operation of the file, you coded it like this:
file1 = open('Orders_Per_Users.txt', 'w')
While the correct mode is 'a' instead of 'w' to append to the file without erasing old written text!
NOTE: even if you correct it to be 'a' another issue will appear! the line will be written again in entering new order!
So what you should do is closing the file file1.close() each time you write to it in the while so your code will be looks like this:
CustomerList = []
Customers = {}
Dates = {}
while True:
Customer_Name = input("Customer's Name:")
CustomerList.append(Customer_Name)
Customers_Address = input("Customer's Address:")
if Customer_Name in Customers:
Customers[Customer_Name]['Orders'] += 1
Customers[Customer_Name]['TotalAmount'] = Total_Amount
else:
Customers[Customer_Name] = {}
Customers[Customer_Name]['Address'] = Customers_Address
Customers[Customer_Name]['Orders'] = 1
Customers[Customer_Name]['TotalAmount'] = 0
file1 = open('Orders_Per_Users.txt', 'a')
file1.write(Customer_Name + " has ordered " + str(Customers[Customer_Name]['Orders']) + " times in total\n")
file1.close()
I am studying JavaScript and Python at the moment, and I am reading and writing to text files in Python at the moment. Currently, I am trying to: write a program that should, when instructed to do so, create a file, that contains a list of students that need to re-sit and the number of marks they need to score to get a minimum of 85.
I have already written code that displays whether or not a student has hit the minimum score of 85, and if they haven't, how many more marks they need. But now I'm stuck. Any help would be very greatly appreciated, thanks!
Python:
def menu():
target = 85
with open('homework.txt','r') as a_file:
for l in a_file:
name, number = l.split(',')
number = int(number)
print(name + ': ' + ('passed' if number>=target else str(target - number)))
input()
Text File:
emma smith,79
noah jones,32
olivia williams,26
liam taylor,91
sophia green,80
mason brown,98
You just need to open a file to write the prints:
def menu():
target = 85
results = open("results.txt",'w')
with open('homework.txt','r') as a_file:
for l in a_file:
name, number = l.split(',')
number = int(number)
results.write(name + ': ' + ('passed' if number>=target else str(target - number)) + '\n')
input()
It sounds like you just want to pipe the results of your program into another textfile.
python file.py > results.txt should do the trick.
(I didn't check your algorithm, as you mention that it's doing what you want it to do already)
I guess this might do what you need ...
def menu():
out_file = open("results.txt", "w")
target = 85
with open("homework.txt", "r") as a_file:
for l in a_file:
name, number = l.split(",")
number = int(number)
out_file.write("{},{}\n".format(name, ('passed' if number>=target else str(target - number))))
menu()
It seems to me that you are trying to achieve the following:
Get the data from a text file, which you kind of did it
Get a user input to open a new text file: reSit = input("Enter file name for the re-sit: ")
Create a file to write to it fh = open(reSit ,'w')
write to a file fh.write(<a fails student> + '\n')
Close the file
if you want to append to a file replace 3 by fh = open(reSit ,'a')
Using windows 10
Here's a sample of my code, where the problem is:
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
At the bottom is the code that writes the information of the list (called fileVar) into the text file (called f). It does write the information to the list but it messes up the order of the lines which cannot happen with the program I am making because the file must be able to be read back to the program to work later on.
Here is my entire code for context:
import os
import string
again = "y"
f = open('accounts.txt', 'a+')
fileVar = f.read().splitlines()
print fileVar
accessedAccount = []
data = f.read()
choice = raw_input("What would you like to do? (add/remove a bank account, access a bank account): ")
if choice == "a":
while again == "y":
accName = raw_input("Account owner's name: ")
accType = raw_input("Account type: ")
accBal = "0"
f.seek(0, 2)
f.write(accName + "\n")
f.write(accType + "\n")
f.write(accBal)
f.write("\n")
again = raw_input("Add another account?: ")
if choice == "a2":
account = raw_input("What is the name of the account you wish to access?: ")
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
print accessedAccount
balance = accessedAccount[2]
intBalance = int(balance)
print accessedAccount
choice2 = raw_input("This is your bank account. What would you like to do now? (Withdraw/deposit, exit): ")
if choice2 == "d":
amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " %intBalance))
newBalance = intBalance + amount
print "Current balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice2 == "w":
amount = int(raw_input("How much money would you like to withdraw? Current balanace: %i : " %intBalance))
newBalance = intBalance - amount
print "Current Balance: %i" %newBalance
f.close()
os.remove("accounts.txt")
f = open ("accounts.txt", "a+")
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
f.write(accessedAccount[0] + "\n")
f.write(accessedAccount[1] + "\n")
newBalance = str(newBalance)
f.write(newBalance + "\n")
for item in fileVar:
f.write("%s\n" %item)
test = raw_input("Waiting for input")
if choice == "r":
removeChoice = raw_input("What is the name of the account you wish to remove?: ")
f.close()
os.remove("accounts.txt")
f= open("accounts.txt", "a+")
for i, line in enumerate(fileVar):
if removeChoice in line:
for j in fileVar[i:i+3]:
accessedAccount.append(j)
fileVar.remove(accessedAccount[0])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[2])
for item in fileVar:
f.write("%s\n" %item)
f.close()
for example, the original text file looks like this:
Ryan
Savings
0
John
Chequings
0
Carly
Savings
0
when it is re-written with edited information, what it is supposed to look like, if 300 dollars were added to Carly's account:
Carly
Savings
300
Ryan
Savings
0
John
Chequings
0
What it looks like instead:
Carly
Savings
300
John
Chequings
Ryan
0
Savings
0
Thank you in advance :)
Not a direct answer to your question, but some pointers which may end up making it much easier for both yourself and others to debug your code.
1) Functions are your friend. See if you can take small tasks and break them up into functions. For example, writing out someone's balance to a file could be a small function, which you might call like:
def write_balance_to_file(account_details):
...function code goes here...
account_details = {name:"Ryan", account:"Savings", balance:1000}
write_balance_to_file(account_details)
Opening and closing the file should be handled within that function, and preferably using:
with open('filename', 'a+') as f:
f.write("A thing to write")
Note that you don't need to close the file manually when doing this.
2) Use a dictionary for storing a person's account details, rather than a list. Multiple accounts can be stored as a list of dictionaries. This makes it a lot easier to read as call such as:
f.write(accessedAccount[0] + "\n")
which becomes:
f.write(accessedAccount['name'] + '\n')
You can then pass in this dictionary to the write_balance_to_file method you will create. :)
3) Consider a tab-separated format for your accounts.txt file. Remember to escape/remove any tabs in your user input. This way each account will be on one line.
4) Possibly a little way in the future for you, but be aware that unit-testing exists, and is good practice. In essence, you can write tests (usually using a test framework such as py.test) which test each function/class/module under different input conditions. Anything that you can't break up into small, testable code fragments (functions or classes) is probably not good code. Writing tests is a great way to identify bugs in your code, and often helps to clarify your thinking. ALWAYS TEST!
For a minimal change that will solve the issue, this is the code that needs to change:
for i, line in enumerate(fileVar):
if account in line:
for j in fileVar[i:i+3]:
print j
accessedAccount.append(j)
This records which entries are part of the accessedAccount however later on you just remove the first occurence of these entries:
fileVar.remove(accessedAccount[2])
fileVar.remove(accessedAccount[1])
fileVar.remove(accessedAccount[0])
but if the entry is something as simple as 0 then it will not necessarily remove it from the correct place, so instead pop the accessed account out of the fileVar when putting them into accessedAccount:
for i, line in enumerate(fileVar):
if account in line:
for j in range(3):
print i+j
accessedAccount.append(fileVar.pop(i+j))
#break # you probably want to stop checking by this point
This will remove the relevent lines from fileVar and put them in accessedAccount so the order of lines will not be messed up by using .remove, and then obviously comment out the calls to .remove:
## fileVar.remove(accessedAccount[2])
## fileVar.remove(accessedAccount[1])
## fileVar.remove(accessedAccount[0])
This should fix the immediate problem of taking out the wrong lines.
I'm writing a program in Python that will store Student IDs, names, and D.O.B.s.
The program gives the user the ability to remove, add, or find a student. Here is the code:
students={}
def add_student():
#Lastname, Firstname
name=raw_input("Enter Student's Name")
#ID Number
idnum=raw_input("Enter Student's ID Number")
#D.O.B.
bday=raw_input("Enter Student's Date of Birth")
students[idnum]={'name':name, 'bday':bday}
def delete_student():
idnum=raw_input("delete which student:")
del students[idnum]
def find_student():
print "Find"
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
add_student()
elif selection == '2':
delete_student()
elif selection == '3':
find_students
elif selection == '4':
break
else:
print "Unknown Option Selected!"
The problem I am having is I cannot figure out how to have the program save any added records to a file when the program ends. It also would need to read back the records when the program restarts.
I keep trying to find tutorials for this sort of thing online, but to no avail. Is this the sort of code I'd want to add?:
f = open("myfile.txt", "a")
I'm new to Python so any help would be appreciated. Thanks so much.
It depends, if you want to actually save python objects, check out Pickle or Shelve, but if you just want to output to a text file, then do the following:
with open('nameOfYourSaveFile', 'w') as saveFile:
#.write() does not automatically add a newline, like print does
saveFile.write(myString + "\n")
Here's an answer that explains the different arguments to open, as in w, w+, a, etc.
As an example, say we have:
with open('nameOfYourSaveFile', 'w') as saveFile:
for i in xrange(10):
saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")
To read the file back, we do:
names = []
numbers = []
emails = []
with open('nameOfYourSaveFile', 'r') as inFile:
for line in inFile:
#get rid of EOL
line = line.rstrip()
#random example
names.append(line[0])
numbers.append(line[1])
emails.append(line[2])
#Or another approach if we want to simply print each token on a newline
for word in line:
print word
import pickle,os
if os.path.exists("database.dat"):
students = pickle.load(open("database.dat"))
else:
students = {}
... #your program
def save():
pickle.dump(students,open("database.dat","w"))