270 likes | 390 Views
COMPSCI 101 S1 2014 Principles of Programming. 10 Reading and writing Strings from file. Recap. number_list = [1, 2, 3] for number in number_list: print (number) print (len(number_list)). A list stores data as a sequence len() returns the number of elements in a list
E N D
COMPSCI 101 S1 2014Principles of Programming 10 Reading and writing Strings from file
Recap number_list = [1, 2, 3] for number in number_list: print (number) print (len(number_list)) • A list stores data as a sequence • len() returns the number of elements in a list • We use a for loop to iterate through the contents of a list • Conditional statements (if, else, elif) • Check the conditions and change the behaviour of the program. • We must use indentation to define the code that is executed, based on whether a condition is met. • Loops • Execute a sequence of statements multiple times if x%2 == 0: print('x is even') if x%2 == 0: print('x is even') else: print('x is odd') ERROR Why? COMPSCI101
Learning outcomes • At the end of this lecture, students should be able to: • understand file structure and file objects • open/close a file • read/write data from/to a file • split a String into a List • read/write Numeric Data • Examples and Exercises • Case study 1: Copying Data • Case study 2: Writing each word on a line • Exercise 1: Counting the number of characters in a file • Exercise 2: Counting the number of words in a file • Exercise 3: Writing two random marks to a file COMPSCI101
10.1 File Structure What is a File? • A file is a collection of data that is stored on a secondary storage like a disk or a thumb drive. • Data stored in a program is temporary. • Accessing a file means establishing a connection between the file and the program and moving data between the two. THE WOODS … The woods … COMPSCI101
10.1 File Structure Two types of Files • Files come in two general types: • Text Files: • designed to be read by human beings, and that can be read or written with an editor • Encoded in ASCII • Binary Files: • designed to be read by programs and that consist of a sequence of binary digits. For example: images, audio, video files, etc. The woods are lovely dark and deep But I have promises to keep And miles to go before I sleep And miles to go before I sleep words.txt COMPSCI101
10.1 File Structure File System • The file system organizes files and folders in a tree structure. • There is a root directory on your computer. • Directories can contain files or other directories. • A complete description of what directories to visit to get to your file is called a path. COMPSCI101
10.1 File Structure Path • The file pathname can be specified in two ways: • Absolute path: • It consists of the sequence of folders, starting from the root directory, that must be traversed to get to the file • Relative path: • It is the sequence of directories that must be traversed, starting from the current working directory, to get to the file. C:\Users\angela\Documents\Ch10Examples\words.txt words.txt Working directory: Ch10Examples COMPSCI101
10.1 File ObjectsFile Objects • When opening a file, you create a file object or file stream that is a connection between the file information on disk and the program. • Reading information into a program: • Writing information from a program. File Object The woods … T h … T File Object … H THE WOODS … COMPSCI101
10.2 Open/CloseOpening and Closing a File • Processing a file consists of these three steps: • Opening a file for reading or writing • Reading from the file and/or writing to the file • Closing the file COMPSCI101
10.2 Opening/ClosingOpening a File • The syntax for opening a file is as follows: • Examples: fileObject = open(filename, mode) Opens a file in the working directory input_file = open("scores.txt", "r") COMPSCI101
10.2 Opening/ClosingFile Objects Demo 01 • Opening a file for reading: • Examples: • Opening a file for writing: • Example: <_io.TextIOWrapper name='words.txt' mode='r' encoding='cp1252'> input_file = open("words.txt", "r") print (input_file) … FileNotFoundError: [Errno 2] No such file or directory: 'words1.txt' input_file = open("words1.txt", "r") print (input_file) output_file = open("output1.txt", "w") print (output_file) <_io.TextIOWrapper name='output1.txt' mode='w' encoding='cp1252'> COMPSCI101
10.2 Opening/Closing Closing a File • The syntax for closing a file is as follows: • The close() functioncloses the file — writes it out to the disk (if writing), and won’t let you do any more to it without re-opening it. • Examples: fileObject.close() input_file.close() output_file.close() COMPSCI101
10.3 Reading/Writing Reading Data Demo 02 • After a file is opened for reading data, you can use the read method to read all characters and return as a single string. • The syntax for reading all characters is as follows: • Examples: fileObject.read() input_file = open("words.txt", "r") contents = input_file.read() print (contents) The woods are lovely dark and deep But I have promises to keep … File object <_io.TextIOWrapper name='words.txt‘ …> print (input_file) input_file.close() COMPSCI101
10.3 Reading/Writing Writing to a File Demo 03 • First, the file must be opened for writing: • If output.txt does not exist, the open() function will create it • If output.txt does exist, its content will be erased. • The syntax for writing a file is as follows: • Examples: • Close the file after we have finished writing output_file = open("output.txt", "w") fileObject.write(string) Python is a great language. output_file.write("Python is a great language.\n") output_file.write("Yeah its great!!\n"); output_file.close() Python is a great language. Yeah its great!! COMPSCI101
10.3 Reading/Writing Appending Data Demo 03B • Again, the file must be opened but use the “a” mode for appending data • Example: • Close the file after we have finished writing Python is a great language. Yeah its great!! output_file = open("output.txt", "a") output_file.write("Python is interpreted\n") output_file.close() Python is a great language. Yeah its great!! Python is interpreted COMPSCI101
10.3 Reading/Writing Case Study 1: Copying Data • Task: • Complete the copy_data()function which takes an input filename and an output filename as input, copies data from the input file to the output file and returns the number of characters in the file. • Arguments: an input filename and an output filename • Returns: The number of characters in the file • Case: 124 copy_data("words.txt", "output.txt") COMPSCI101
10.3 Reading/Writing Copying Data Demo 04 • Algorithm: contents = input_file.read() output_file.write(contents) COMPSCI101
Exercise 1 Exercise1:Counting the Number of Characters • Task: • Complete the count_characters() function which takes the name of a file as input and returns the number of characters in the file. • Arguments: an input filename • Returns: The number of characters in the file • Algorithm: COMPSCI101
10.4 Splitting a String to a ListSplitting a String to a List Demo 05 • The split()method splits items in a string into a list. • Example: • Items are delimited by spaces in the string. • The split() method returns a list message = "Welcome to COMPSCI101" words = message.split() print(words) ['Welcome', 'to', 'COMPSCI101'] print (type(words)) <class 'list'> COMPSCI101
10.4 Splitting a String to a ListThe delimiter String Demo 06 • The syntax for splitting a string is as follows: • Parameter: str – • Specifies the character to use for separating the string (delimiter) • By default, it is a space. • Examples: string.split(str) Delimiter: “,” s = "12,23,34,45" words = s.split(",") print (words) ['12', '23', '34', '45'] COMPSCI101
Exercise 2 Exercise 2: Counting the Number of WORDS • Task: • Complete the count_words()function which takes the name of a file as input and returns the number of words in the file. • Arguments: an input filename • Returns: The number of words in the file • Algorithm: COMPSCI101
Case Study 2Writing Each Word on a Line • Task: • Complete the copy_words() function which takes two parameters as input: an input file name and an output file name. The function should read and write one word at a time, and return the number of words read. • Arguments: an input filename and an output filename • Returns: the number of words read • Case: 27 copy_words("words.txt", "output.txt") The woods are lovely dark and deep But I have promises to keep And miles to go before I sleep And miles to go before I sleep The Woods are … COMPSCI101
Case Study 2Writing Each Word on a Line Try Demo 7 • Algorithm: COMPSCI101
10.5 Writing/Reading Numeric DataWriting Numeric Data Demo 08 • To write numbers, convert them into strings, and then use the write method to write them to a file. • In order to read the numbers back correctly, you should separate the numbers with a whitespace character such as ' ', '\n'. • Examples: • Note: • The str() function • Returns a string containing a nicely printable representation of an object Number: must be str, not int for number in [10, 20, 30, 40]: output_file.write(number) WRONG! 10203040 for number in [10, 20, 30, 40]: output_file.write(str(number)) for number in [10, 20, 30, 40]: output_file.write(str(number)) output_file.write(" ") COMPSCI101
10.5 Writing/Reading Numeric DataReading Numeric Data Demo 08 • To read numbers, read all contents from a file, then split the contents into a list and convert it back into an integer one at a time if you need to do a calculation • Example: • Note: • The int()function • Convert a number or string x to an integer input_file = open("numbers.txt", "r") contents = input_file.read() words = contents.split() for word in words: number = int(word) print (number * 2) COMPSCI101
Case Study 3: Writing Random Numbers Try Demo 09 • Task: • Complete the write_random()function which takes output filename as input, writes two random marks to the output file • Arguments: an output filename • Case: • Algorithm write_random("words.txt", "marks.txt") COMPSCI101
Summary • You can use file objects to read/write data from/to files. You can open a file to create a file object with mode r for reading, w for writing, and a for appending. • You can use the read() method to read data from a file. • You can use the write() method to write data to a file. • You should close the file after the file is processed to ensure that the data is saved properly. COMPSCI101