Question

In: Computer Science

Objective Work with strings Work with files Work with formatted output This program will display a...

Objective Work with strings

Work with files

Work with formatted output

This program will display a very basic handling of transactions for a checking account. The program will read in a data file with all the past transactions. Use FileUtil.selectOpenFile or input() to get a file name from the user. The format of the file will be very basic, just a date (as a string in the format of MM/DD), a single letter which indicates the type of transaction (‘B’ for beginning balance, ‘C’ for a check, ‘D’ for a deposit, or ‘W’ for a withdrawl) and an amount (floating point value). The transaction type may be upper or lower case, but there are string methods which make this a nonissue. The first line of the data WILL BE the beginning balance. The remaining lines may be for any type of transaction other than specifying the beginning balance. All lines will have three values, separated by commas, and in the order specified. An sample data file might be:

10/01,B,1000.00

10/02,C,100.00

10/03,C,9.00

10/04,C,50.00

10/04,W,20.00

You do not need to write a program to create the data file, you can use any text editor. You can write a program to create the file if you want, but you don’t need to turn it (don’t turn it in ??) and you won’t receive extra credit for it. After reading each line, break it up into its inidivual pieces of information. The split() method would likely be the easiet way to do so, but you can use the find() or index() methods as well. Write the information from the data file to the display in a neat, column-aligned format with an updated balance on each line. Expand the single letter for the transaction type into complete text, as demonstrated below. Make sure each dollar amount has exactly 2 places after the decimal point. Also include today’s date at the top of the table. A simple search using “Python” and “today’s date” will provide the info on how to access the current date from the system clock. We also did this in an example in class, so that might be the quickest place to check.

A sample of the output, using the data from above, might be: Checkbook balance as of 10/26 10/01 Beginning Balance 1000.00 10/02 Check 100.00 900.00 10/03 Check 9.00 891.00 10/04 Withdrawal 20.00 871.00 10/05 Check 50.00 821.00

Solutions

Expert Solution

Here I am giving solution using two ways (chnages only in output display)

1. Using prettytable to create table in output

2. Without using prettytable

1. Using prettytable to create table in output

Here i am using prettytable package of python to create a table. So first install the package using below instruction:

pip install prettytable

Code:

from prettytable import PrettyTable # Used to create a table
from datetime import datetime # used to get current date

x = PrettyTable() # create tabel

x.field_names = ["Date (MM/DD)", "Type of Transaction", "Amount", "Balance"] # Give name of column in table

# Create dictionary of transaction type
trans_type = {'B' : 'Beginning Balance', 'C' : 'Check', 'D' : 'Deposit', 'W': 'Withdrawal', 'b' : 'Beginning Balance', 'c' : 'Check', 'd' : 'Deposit', 'w': 'Withdrawal'}

# Take filename from user
filename = input('Enter File Name ')

# Try to handle file not found error
try:

with open(filename) as fp: # Open a file
line = fp.readline() # Read line from file

while line:

line = line.rstrip('\n') # Remove newline chacater from line

data = line.split(',') # Split the line data

if data[1] == 'B' or data[1] == 'b': # if transaction type is 'B' or 'b'
x.add_row([data[0],trans_type[data[1]],'-----',data[2]]) # Add data into table row
bal = float(data[2]) # Store the balance into bal variable
  
elif data[1] == 'C' or data[1] == 'c': # if transaction type is 'C' or 'c'
x.add_row([data[0],trans_type[data[1]],data[2], bal - float(data[2])]) # Add data into table row
bal = bal - float(data[2]) # Update the balance
  
elif data[1] == 'D' or data[1] == 'd': # if transaction type is 'D' or 'd'
x.add_row([data[0],trans_type[data[1]],data[2],bal + float(data[2])]) # Add data into table row
bal = bal + float(data[2]) # Update the balance
  
elif data[1] == 'W' or data[1] == 'w': # if transaction type is 'W' or 'w'
x.add_row([data[0],trans_type[data[1]],data[2],bal - float(data[2])]) # Add data into table row
bal = bal - float(data[2]) # Update the balance

line = fp.readline() # Read line from file

# Print the message with current month and day
print('\n\n\t\tCheckbook Balance as of',str(datetime.now().month)+'/'+str(datetime.now().day))
  
print(x) # Print table   

except FileNotFoundError: # If file not found
print("File does not exist") # Print a message

Output:

2. Without using prettytable

from datetime import datetime # used to get current date

# Create dictionary of transaction type
trans_type = {'B' : 'Beginning Balance', 'C' : 'Check', 'D' : 'Deposit', 'W': 'Withdrawal', 'b' : 'Beginning Balance', 'c' : 'Check', 'd' : 'Deposit', 'w': 'Withdrawal'}

# Take filename from user
filename = input('Enter File Name ')

# Print the message with current month and day
print('\n\n\t\tCheckbook Balance as of',str(datetime.now().month)+'/'+str(datetime.now().day))
print("\nDate (MM/DD)", '\t',"Type of Transaction", '\t',"Amount", '\t',"Balance\n")
print('------------------------------------------------------------------------\n')

# Try to handle file not found error
try:

with open(filename) as fp: # Open a file
line = fp.readline() # Read line from file

while line:

line = line.rstrip('\n') # Remove newline chacater from line

data = line.split(',') # Split the line data

if data[1] == 'B' or data[1] == 'b': # if transaction type is 'B' or 'b'
print(data[0],'\t\t',trans_type[data[1]],'\t',' ','\t\t',data[2])
bal = float(data[2]) # Store the balance into bal variable
  
elif data[1] == 'C' or data[1] == 'c': # if transaction type is 'C' or 'c'
print(data[0],'\t\t',trans_type[data[1]],'\t\t ',data[2],'\t\t',bal - float(data[2]))
bal = bal - float(data[2]) # Update the balance
  
elif data[1] == 'D' or data[1] == 'd': # if transaction type is 'D' or 'd'
print(data[0],trans_type[data[1]],data[2],bal + float(data[2]))
bal = bal + float(data[2]) # Update the balance
  
elif data[1] == 'W' or data[1] == 'w': # if transaction type is 'W' or 'w'
print(data[0],'\t\t',trans_type[data[1]],'\t ',data[2],'\t\t',bal - float(data[2]))
bal = bal - float(data[2]) # Update the balance

line = fp.readline() # Read line from file

except FileNotFoundError: # If file not found
print("File does not exist") # Print a message

Output:

;Please thumbs up for my solution.


Related Solutions

Basic Unix Commands Objective: The objective of this lab is to work with files of UNIX...
Basic Unix Commands Objective: The objective of this lab is to work with files of UNIX file system. Procedure: 1. OpenyourUnixshellandtrythesecommands: Ø Create a new file and add some text in it vcat > filename Ø View a file vcat /etc/passwd vmore /etc/passwd vmore filename Ø Copy file, making file2 vcp file1 file2 Ø Move/rename file1 as file2 vmv file1 file2 Ø Delete file1 as file2 vrm file //Deletefile //Double-checkfirst vrm -i file Ø Counts the lines, words, characters in...
PYTHON...... Working with lists, functions, and files Objective: Work with lists Work with lists in functions...
PYTHON...... Working with lists, functions, and files Objective: Work with lists Work with lists in functions Work with files Assignment: Part 1: Write a program to create a text file which contains a sequence of test scores. Ask for scores until the user enters an empty value. This will require you to have the scores until the user enters -1. After the scores have been entered, ask the user to enter a file name. If the user doesn’t not enter...
Objectives: Practice using files and strings. More practice using loops with files and strings Background Assume...
Objectives: Practice using files and strings. More practice using loops with files and strings Background Assume you're working on a contract where the company is building a e-mailing list. Your task is to write a C++ program that reads through an e-mail stored in the current working directory, called mail.dat, and outputs every email address found as individual lines to a file called email_list.dat. For this assignment, if a whitespace delimited string of characters has an embedded commercial at sign...
ACTIVITY #1: Defining Strings √ Write an assembly program that display your name, your id, and...
ACTIVITY #1: Defining Strings √ Write an assembly program that display your name, your id, and your college name on the screen. √ Remember: the format of the assembly program should be like this. TITLE your title (FileName.asm) .MODEL FLAT .386 .STACK 64 .DATA str1 DB "My name: Essam Alnatsheh",13,10,'$' .CODE main PROC mov ax,@data mov ds,ax mov ah,09h mov dx, offset str1 int 21h ​mov ah,4Ch​​ ; terminate process ​mov al,0​​ ; return code ​int 21h main ENDP END...
Objectives: Write a program which reads User Input using Scanner Print formatted output using printf or...
Objectives: Write a program which reads User Input using Scanner Print formatted output using printf or DecimalFormat Practice programming simple mathematical calculations Instructions: Samwise Gamgee has finally decided to submit his expense report for all of his adventures regarding his travels to Mordor. Part of those expenses are his stay at the Prancing Pony Inn located in Bree. You are to write a simple Java program which will generate an Invoice for his stay at the Inn. Your program should...
Creation of Program Application (Development Task 1) This program should create two output files. You may...
Creation of Program Application (Development Task 1) This program should create two output files. You may use .txt files. Create the following files: Deposists.txt Withdrawls.txt 1. The program application should have the following inputs: Amount for Deposits (Only Accept Positive Amounts) Amount for Withdrawals (Only Accept Positive Amounts). The subsequent program will subtract the positive amount. 2. The program application should have the following outputs: Deposists.txt Withdrawals.txt Total of Deposits and Withdrawals back to the console
I want the program to use 1- D array and display a table as output. Write...
I want the program to use 1- D array and display a table as output. Write a script to simulate the rolling of two dice. The script should use Math.random to roll the first die and again to roll the second die. The sum of the two values should then be calculated. [Note: Since each die can show an integer value from 1 to 6, the sum of the values will vary from 2 to 12, with 7 being the...
write both non-recursive and recursive functions that take the strings from the user and display strings...
write both non-recursive and recursive functions that take the strings from the user and display strings in backwards in python
PLEASE DO IN C# Warehouse Inventories Objective: Work with multiple objects and review reading data files....
PLEASE DO IN C# Warehouse Inventories Objective: Work with multiple objects and review reading data files. Description: A wholesale distributor has six warehouses (Atlanta, Baltimore, Chicago, Denver, Ely and Fargo) and sells five different items (identified by part number: 102, 215, 410, 525 and 711). Each warehouse may stock any or all of the five items. The company buys and sells these items constantly. Company transaction records contain a transaction code (‘P’ for a purchase or ‘S’ for a sale)...
Warehouse Inventories Objective: Work with multiple objects and review reading data files. Description: A wholesale distributor...
Warehouse Inventories Objective: Work with multiple objects and review reading data files. Description: A wholesale distributor has six warehouses (Atlanta, Baltimore, Chicago, Denver, Ely and Fargo) and sells five different items (identified by part number: 102, 215, 410, 525 and 711). Each warehouse may stock any or all of the five items. The company buys and sells these items constantly. Company transaction records contain a transaction code (‘P’ for a purchase or ‘S’ for a sale) followed by an item...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT