Fundamentals of Programming I Files

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

P3- Represent how data flows around a computer system
Computer Science 111 Fundamentals of Programming I Files.
Why use Files? Your Python Program External File (secondary storage) Write to file (Save) Read from file (Load) …so we can have access to ‘stored’ data.
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Computer Hardware.
CS 0008 Day 2 1. Today Hardware and Software How computers store data How a program works Operators, types, input Print function Running the debugger.
Topics This week: File input and output Python Programming, 2/e 1.
Random access memory is a form of computer data storage. A random-access device allows stored data to be accessed directly in any random order.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 17 Reading and Writing Files 5/10/09 Python Mini-Course: Lesson 17 1.
Computer System Overview Chapter 1. Operating System Exploits the hardware resources of one or more processors Provides a set of services to system users.
Outcome 2 – Computer Software The Range of Software Available The Different Categories of Software System Software Programming Languages Applications Software.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Chapter 1 Basic Structure of Computers. Chapter Outline computer types, structure, and operation instructions and programs numbers, arithmetic operations,
1 Introduction to Computers Prof. Sokol Computer and Information Science Brooklyn College.
2.0 Computer System.
Intro to Computers Computer Apps 1.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
1 CS161 Introduction to Computer Science Topic #13.
What is a computer? Computer is a device for processing information.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
File I/O Michael Ernst UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Computer Basic Vocabulary
File I/O Ruth Anderson UW CSE 160 Spring File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
Computer Fundamentals/ Organizing Your Work/ 1 of 16.
Using Text Files in Excel File I/O Methods. Working With Text Files A file can be accessed in any of three ways: –Sequential access: By far the most common.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
“Read Only Memory” a class of storage media used in computers and other electronic devices. This tells the computer how to load the operating system.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
File I/O Ruth Anderson UW CSE 140 Winter File Input and Output As a programmer, when would one use a file? As a programmer, what does one do with.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Introduction To Computers
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
INTRODUCTION TO COMPUTERS. A computer system is an electronic device used to input data, process data, store data for later use and produce output in.
WHAT IS COMPUTER ? . A computer is a complex system consisting of both hardware and software components.
Computer Architecture and Number Systems
Computer Science II Chapter 1.
Topic: File Input/Output (I/O)
Fundamentals of Python: First Programs
Chapter 7 Text Input/Output Objectives
File I/O File input/output Iterate through a file using for
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
CSCI 161: Introduction to Programming
Ruth Anderson UW CSE 160 Winter 2016
Exceptions and files Taken from notes by Dr. Neil Moore
Introduction to Computers
Binary Files.
Ruth Anderson UW CSE 160 Winter 2017
Ruth Anderson UW CSE 160 Spring 2018
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
Exceptions and files Taken from notes by Dr. Neil Moore
Introduction to Computers
Logical Computer System
Files Handling In today’s lesson we will look at:
Fundamentals of Python: First Programs
15-110: Principles of Computing
Topics Introduction to File Input and Output
Topics Introduction to File Input and Output
Introduction to Computer Science
Presentation transcript:

Fundamentals of Programming I Files Computer Science 111 Fundamentals of Programming I Files

Data Storage Data (and programs) are loaded into primary memory (RAM) for processing From where? From input devices (keyboard, microphone) From secondary memory - a hard disk, a flash stick, a CD, or a DVD

Primary and Secondary Storage Integrated circuits on wafer-thin chips Hard disk CD DVD Flash Primary Memory (RAM) Processor Secondary memory Very fast Expensive Transient Slower Cheaper Permanent I/O devices Keyboard Mouse Microphone Monitor Speakers

What Is a File? A file is a software object that allows a program to represent and access data stored in secondary memory Two basic types of files: Text files: for storing and accessing text (characters) Binary files: executable programs and their data files (such as images, sound clips, video)

Text Files A text file is logically a sequence of characters Basic operations are input (read characters from the file) output (write characters to the file) There are several flavors of each type of operation

File Input We want to bring text in from a file for processing Three steps: Open the file for input Read the text and save it in a variable Process the text

Opening a File <a flag> can be <a variable> = open(<a file name>, <a flag>) <a flag> can be 'r' - used for input, to read from an existing file 'w' - used for output, to overwrite an existing file 'a' - used for output, to append to an existing file

Example: Read Text from a File filename = input('Enter a file name: ') myfile = open(filename, 'r') text = myfile.read() print(text) The file name must either be in the current directory or be a pathname to a file in a directory Python raises an error if the file is not found text refers to one big string

Read Lines of Text from a File filename = input('Enter a file name: ') myfile = open(filename, 'r') for line in myfile: print(line) The variable line picks up the next line of text on each pass through the loop line will contain the newline character, so the echo will print extra blank lines

Read Lines of Text from a File filename = input('Enter a file name: ') myfile = open(filename, 'r') for line in myfile: print(line[:-1]) Extract a substring up to but not including the last character (the newline) This will produce an exact echo of the input file

Alternatively, Use readline filename = input('Enter a file name: ') myfile = open(filename, 'r') while True: line = myfile.readline() if line == '': break print(line[:-1]) The readline method reads a line of text and returns it as a string, including the newline character This method returns the empty string if the end of file is encountered

Count the Words filename = input('Enter a file name: ') myfile = open(filename, 'r') wordcount = 0 for line in myfile: wordcount += len(line.split()) print('The word count is', wordcount)

File Output We want to save data to a text file Four steps: Open the file for output Covert the data to strings, if necessary Write the strings to the file Close the file

Example: Write Text to a File filename = input('Enter a file name: ') myfile = open(filename, 'w') myfile.write('Two lines\nof text') myfile.close() If the file already exists, it is overwritten; otherwise, it is created in the current directory or path The write method expects a string as an argument Failure to close the file can result in losing data

Example: Write Integers to a File filename = input('Enter a file name: ') myfile = open(filename, 'w') for i in range(1, 11): myfile.write(str(i) + '\n') myfile.close() write can be called 0 or more times Data values must be converted to strings before output Separators, such as newlines or spaces, must be explicitly written as well

Managing Directories D D F F F D F F F F D F F F Directories are organized in a tree-like structure Python’s os module includes many functions for navigating through a directory system and managing it D D F F F D F F F F D F F F

os Functions Function What It Does os.getcwd() Returns the current working directory (string) os.chdir(path) Attaches to the directory specified by path os.listdir(path) Returns a list of the directory’s contents os.remove(name) Removes a file at path os.rename(old, new) Resets the old path to the new one os.removedirs(path) Removes the directory (and all subdirectories) at path

os.path Functions Function What It Does os.path.exists(path) Returns True if path exists or False otherwise. os.path.isdir(path) Returns True if path names a directory or False otherwise. os.path.isfile(path) Returns True if path names a file or False otherwise. os.path.getsize(path) Returns the size of the object named by path in bytes.

Example: Does the File Exist? import os.path filename = input('Enter a file name: ') if not os.path.exists(filename): print('Error: the file not not exist!') else: myfile = open(filename, 'r') print(myfile.read()) myfile.close()

For Monday Start Chapter 5