Review Basic File I/O

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Review basic file I/O

Files Created: pcost.py


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FileHandlingGroup -.-> python/file_opening_closing("`Opening and Closing Files`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132392{{"`Review Basic File I/O`"}} python/with_statement -.-> lab-132392{{"`Review Basic File I/O`"}} python/variables_data_types -.-> lab-132392{{"`Review Basic File I/O`"}} python/numeric_types -.-> lab-132392{{"`Review Basic File I/O`"}} python/type_conversion -.-> lab-132392{{"`Review Basic File I/O`"}} python/for_loops -.-> lab-132392{{"`Review Basic File I/O`"}} python/lists -.-> lab-132392{{"`Review Basic File I/O`"}} python/tuples -.-> lab-132392{{"`Review Basic File I/O`"}} python/file_opening_closing -.-> lab-132392{{"`Review Basic File I/O`"}} python/build_in_functions -.-> lab-132392{{"`Review Basic File I/O`"}} end

Working with files

The file portfolio.dat contains a list of lines with information on a portfolio of stocks. The file looks like this:

AA 100 32.20
IBM 50 91.10
CAT 150 83.44
MSFT 200 51.23
GE 95 40.37
MSFT 50 65.10
IBM 100 70.44

The first column is the stock name, the second column is the number of shares, and the third column is the purchase price of a single share.

Write a program called pcost.py that opens this file, reads all lines, and calculates how much it cost to purchase all of the shares in the portfolio. To do this, compute the sum of the second column multiplied by the third column. Finally, output the results of the calculation.

Summary

Congratulations! You have completed the Review Basic File I/O lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like