You are on page 1of 31

Program design

& Session# 3
Text files
This Lecture
• Session-02 review
• Program Design
• Pseudocode
• files
• Reading from files
• Writing to files
• Updating files
Arithmetic Operators
• +, -, *, /, **, //, %, abs() ** exponentiation
+ addition
// integer division
- subtraction
% Modulo
* multiplication
abs() absolute value
/ division
String of characters
• My_str = ‘Win college’;
• ‘Win college’ is stored in a string my_str.
• We can access individual characters.
• Print(my_str[0]) → W
• Print(my_str[3]) → ‘ ‘

• Storage
Program to add given number of numbers
Adding Numbers - Logic
• To find the total of a list of numbers we,
• Start with a total of 0 (referred to as initialising the total)

• Add each number to the progressive total is until all the numbers
are added

• E.g. Add 4 numbers


• Number to add 2 8 -1 5
total becomes 0 2 10 9 14
6
Pseudocode

• The logic of a program is independent of the syntax

• Pseudocode shows the logic of the program without worrying

about the syntax (specific to the programming language)

28 November, 2020 7
Problem Pseudocode
• To add numbers entered:
1. Initialise the total

2. Input how many numbers to be added

3. Use a definite loop to input each number and add it to the total

4. Display the total

8
Program structure
• Comments are generated from the pseudocode to create the structure of the
program
# program to find total of all numbers entered
# input how many numbers will be entered
# initialise total to 0
# definite loop
# enter a number
# add the number to the total
# display the total

• Note indentation

9
Program code
# program to find the total of all numbers entered
def main():
# input how many numbers will be entered
count = input("How many numbers will be entered? ")
# initialise total to 0
total = 0

10
Program code cont.
# repeat ‘count’ times
for index in range(count):
# enter a number
num = input("Enter a number: ")
# add the number to the total
total = total + num
# display the total
print "The total of these ", count, "numbers is ", total
main() # execute the program

11
Modifying the code – Class Exercise
• Open the file week2-1.py from last weeks lab and change the code to
do Multiplication.

• If you don’t have a copy of it, ask the lecturer for a copy of the code.

12
Finding the product
• With 2,3,4,5 we want the progressive product to be:
2, 6, 24, 120

• Initial value of product is not 0, as 0 times 3 is not 3.

• Instead we must use 1.

13
Modifications required
• Use product throughout (instead of total)

• Initialise product to 1 (instead of 0)

• Progressive product is obtained by:


product = product * num (* not +)

14
Data Files
• Files are stored in secondary memory (hard disk)

• They have a unique pathname that enables the operating system to


access them for processing
• Ex: C:\programming fundamentals\week-03\addNumber.py
• File name is at the last.
• Start from the hard disk name (root)
• Shows all the path

15
Text files
• Consist of alphabetic characters, numbers, punctuation and special
characters.

• Created using Notepad and saving the file.

• Special characters include:


• ‘/n’ - newline
• ‘/t’ - tab

16
File operations
• Reading
• Reading Data from a file on Hard disk to memory (RAM)

• Writing
• Writing data from RAM to a newly created file on Hard disk.
• Note: Writing to an existing file overwrites the original data in that file

• Appending
• Adding data to the end of an existing file

17
Reading data

Main Memory
Secondary
(RAM) Memory
HDD
Data transfer
File File
buffer

File pointer: infile infileName

18
Problem Pseudocode
• Read a text file and display (FileReading.py):
1. Define a file pointer.

2. Open the file to read in reading mode.

3. For a line in the file

1. Read the line

2. Print the line

4. Close the file pointer.

19
Program structure
• Comments are generated from the pseudocode to create the structure of the
program

# open a file for reading


# definite loop
# read the file a line at a time
# display the line
# close the file

• Note indentation

20
Code to read a text file
# program to read and display a text file
def main():
# open the file for reading
infile = open(infileName, 'r’);
#read the file a line at a time
for line in infile:
# display the line
print(line[:-1]) # removes the '\n' character
# close the file
infile.close()

main()

21
Testing- Students.txt
• To test the program, there needs to be a text file available
• Lets use –students.txt

• This file can be created in Notepad

• It is important that each line, particular the last, has ‘\n’ at the end

• The newline character is provided by the <Enter> key.

22
Problem Pseudocode
• Writing to a text file (FileWriting.py)
1. Define a file pointer.

2. Open the file for writing in writing mode.

3. Define a string to write

4. Write the string to the file.

5. Close the file pointer.

23
Program structure
• Comments are generated from the pseudocode to create the structure of the program

# open the file for writing using a file pointer outfile

#define a string myStr

# write myStr to the file.

# close the file

• Note indentation

24
Code

# program to write two strings to a text file


def main():
# open the file for writing
outfile = (outfileName, ‘w’)
# enter write two strings to the file
outfile.write(“Hello! This is my attempt to create a text file \n Yeah! Its great \n” )#
add newline at end
#close the file
outfile.close()
main()

25
Problem Pseudocode
• Writing to a text file (FileAppend.py)
1. Define a file pointer to open a file to read. Call it infile
2. Define a file pointer to open a file to append. Call it Outfile.
3. Open the file for reading.
4. Open the file for appending.
5. Use a for loop to read a line from infile
1. Write the line to the Outfile.

6. Close infile.

7. Close Outfile.

26
Program structure
• Comments are generated from the pseudocode to create the structure of the program

# open the infile for reading

# open the outfile for appending

# read the infile a line at a time append data from infile to outfile

#write the line to the output file

#close the infile.

#close the outfile.


• Note indentation

27
Code
• def main():
• infile = open('students1.txt', 'r’); # open the infile for reading
• outfile = open('students2.txt', 'a’); # open the outfile for appending
• # read the infile a line at a time append data from infile to outfile
• for line in infile:
• outfile.write(line);
• infile.close(); #close the infile.
• outfile.close(); #close the outfile.
• main()
Notes

• The file that has been read (students1.txt) is unchanged

• The file opened to append data has new data (as well as old data).

29
Summary
• Program design starts with understanding the logic, developing
pseudocode and designing the program structure. Coding comes at
the end.
• Input from and output to files is much quicker than using
input/output devices
• Files can be opened for reading, writing or appending
• Processing of text files generally involves dealing with a line at a time
• Closing files provides an important tidying up function

30
Tomorrow’s Lecture
• Functions
• Built-in functions
• Libraries
• User defined functions

You might also like