Python: File Management Damian Gordon. File Management We’ve seen a range of variable types: – Integer Variables – Real Variables – Character Variables.

Slides:



Advertisements
Similar presentations
Introduction to File I/O How to read & write data to a disk file...
Advertisements

File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
CHAPTER 11 FILE INPUT & OUTPUT Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
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.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
IDL Tutorials : Day 5 Michael Hahn
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Why python? Automate processes Batch programming Faster Open source Easy recognition of errors Good for data management What is python? Scripting programming.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 11: 1 CMT1000: Introduction to Programming Ed Currie Lecture 10: File Input.
Chapter 8 Overview – Learn to use try catch blocks – Learn to use streams – Learn to use text files.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
V Avon High School Tech Club Agenda Old Business –Delete Files New Business –Week 18 Topics: Intro to HTML/CSS: Questions? Summer Work Letter.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 17 Reading and Writing Files 5/10/09 Python Mini-Course: Lesson 17 1.
Imperative Programming
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Python Programming Using Variables and input. Objectives We’re learning to make use of if statements to enable code to ask questions. Outcomes Build an.
Hans-Peter Plag October 16, 2014 Session 3 Programming Languages Data Types and Variables Expressions and Operators Flow Control.
PYTHON. Python is a high-level, interpreted, interactive and object- oriented scripting language. Python was designed to be highly readable which uses.
By the end of this session you should be able to...
Hans-Peter Plag November 6, 2014 Session 4 (Programming Languages) (Data Types and Variables) Expressions and Operators Flow Control.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
Lecture 26: FILING HANDLING in C Language FILING HANDLING in C Language-1 Lecture 26.
Chapter 12 Using data files. The concept of file Logically cohesive data stored on a permanent storage, such as hard disk (most cases), CD, USB. Types.
Java Chapter 9 File Input and Output. Objectives In this chapter you will: Learn how bits, characters, records, and files fit into a data hierarchy Explore.
For loops in programming Assumes you have seen assignment statements and print statements.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Data Structures: Arrays Damian Gordon. Arrays Imagine we had to record the age of everyone in the class, we could do it declaring a variable for each.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
You Need an Interpreter!. Closing the GAP Thus far, we’ve been struggling to speak to computers in “their” language, maybe its time we spoke to them in.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Files Tutor: You will need ….
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Python – May 12 Recap lab Chapter 2 –operators –Strings –Lists –Control structures.
C OMPUTER P ROGRAMMING 1 Input and Variables. I/O S TATEMENTS : I NPUT & V ARIABLES Input is the term used to describe the transfer of information from.
Data Structures: Multi-Dimensional Arrays Damian Gordon.
Python: Revision Damian Gordon. Python: Structured Programming Damian Gordon.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 10: Files.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”
CST 1101 Problem Solving Using Computers
Topic: File Input/Output (I/O)
Introduction to programming in java
Iterator Pattern: Comprehensions
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lecture Note Set 1 Thursday 12-May-05
Starter Write a program that asks the user if it is raining today.
File Handling Programming Guides.
Topics Introduction to File Input and Output
Using files Taken from notes by Dr. Neil Moore
File Handling.
Fundamentals of Data Structures
Coding Concepts (Basics)
Input and Output with FILES
Text / Serial / Sequential Files
Lesson 08: Files Class Chat: Attendance: Participation
Fundamentals of Python: First Programs
Topics Introduction to File Input and Output
BO65: PROGRAMMING WRITING TO TEXT FILES.
Reading Data From and Writing Data To Text Files
Python: Sorting – Selection Sort
Topics Introduction to File Input and Output
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Python: File Management Damian Gordon

File Management We’ve seen a range of variable types: – Integer Variables – Real Variables – Character Variables – String Variables – Arrays – Linked Lists X 5

File Management The only problem with variables is that once the program has finished running, they cease to exist and all the values they had are forgotten. In formal terms “variables only persist while the program is running”.

File Management It would be good if there were some way to recall some values beyond the persistence of the programs. We can do this with FILES.

File Management We can WRITE data (and variables) to a file to permanently store them, and we can READ the data into other programs. Imagine opening a Notepad file and typing the values of the variables you wish to store into the file, that’s what we can do in Python.

File Management We’ll start off with READing from a file, so let’s assume we’ve created a file already in Notepad, and we are using Python to read the values out of it. We’ll call the file MyData.txt.

File Management Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale. MyData.txt

Reading Text Files

File Management We use the open() and the read() commands:

File Management # PROGRAM FileReader1 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read()) file_pointer.close() # END.

File Management # PROGRAM FileReader1 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read()) file_pointer.close() # END. This program opens a file called MyData.txt for READing, and prints out the whole file.

File Management # PROGRAM FileReader2 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read(20)) file_pointer.close() # END.

File Management # PROGRAM FileReader2 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read(20)) file_pointer.close() # END. This program opens a file called MyData.txt for READing, and prints out the first 20 characters from the file.

File Management # PROGRAM FileReader3 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read(20)) file_pointer.close() # END.

File Management # PROGRAM FileReader3 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.read(20)) file_pointer.close() # END. This program opens a file called MyData.txt for READing, and prints out the first 20 characters from the file, and then it prints out the next 20 characters.

File Management # PROGRAM FileReader4 PathName = "C:\\Python34\\" NameOfFile = str(input("What File would you like to read:")) Extension = ".txt" FullFileName = PathName + NameOfFile + Extension NumberOfChars = int(input("How many characters: ")) file_pointer = open(FullFileName, "r") print(file_pointer.read(NumberOfChars)) file_pointer.close() # END.

File Management # PROGRAM FileReader4 PathName = "C:\\Python34\\" NameOfFile = str(input("What File would you like to read:")) Extension = ".txt" FullFileName = PathName + NameOfFile + Extension NumberOfChars = int(input("How many characters: ")) file_pointer = open(FullFileName, "r") print(file_pointer.read(NumberOfChars)) file_pointer.close() # END. This program asks the user for a filename and a number of characters, and it opens the specified file for READing, and prints out the specified number of characters from the file.

File Management # PROGRAM FileReader4 PathName = "C:\\Python34\\" NameOfFile = str(input("What File would you like to read:")) Extension = ".txt" FullFileName = PathName + NameOfFile + Extension NumberOfChars = int(input("How many characters: ")) file_pointer = open(FullFileName, "r") print(file_pointer.read(NumberOfChars)) file_pointer.close() # END. This program asks the user for a filename and a number of characters, and it opens the specified file for READing, and prints out the specified number of characters from the file. >>> What File would you like to read: MyData How many characters do you want to print: 43 Python is a widely used high-level, general

File Management Now let’s look at the open() command used in conjunction with the readline() command:

File Management # PROGRAM FileReader5 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.readline()) file_pointer.close() # END.

File Management # PROGRAM FileReader5 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.readline()) file_pointer.close() # END. This program opens a file called MyData.txt for READing, and prints out the first line only of the file.

File Management # PROGRAM FileReader6 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.readline(100)) file_pointer.close() # END.

File Management # PROGRAM FileReader6 file_pointer = open("C:\Python34\MyData.txt", "r") print(file_pointer.readline(100)) file_pointer.close() # END. This program opens a file called MyData.txt for READing, and prints out the first 100 characters from the first line only of the file (if there is less than 100 characters, it keeps on printing until it reaches the end of the line).

File Management # PROGRAM FileReader7 file_pointer = open("C:\Python34\MyData.txt", "r") for line in file_pointer: # DO print(line) # ENDFOR; file_pointer.close() # END.

File Management # PROGRAM FileReader7 file_pointer = open("C:\Python34\MyData.txt", "r") for line in file_pointer: # DO print(line) # ENDFOR; file_pointer.close() # END. This program opens a file called MyData.txt for READing, prints out the whole file line by line.

Writing Text Files

File Management To WRITE to a file we use the open() and the write() commands:

File Management # PROGRAM FileWriter1 file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.write("This is a new message")) file_pointer.close() # END.

File Management # PROGRAM FileWriter1 file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.write("This is a new message")) file_pointer.close() # END. This program opens a file called MyData2.txt for WRITing, and creates a new file if there isn’t one there, or overwrites the text in the file if it exists.

File Management # PROGRAM FileWriter2 file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.write("This is a new message\n")) print(file_pointer.write("This is a second message\n")) file_pointer.close() # END.

File Management # PROGRAM FileWriter2 file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.write("This is a new message\n")) print(file_pointer.write("This is a second message\n")) file_pointer.close() # END. This program opens a file called MyData2.txt for WRITing, and creates a new file if there isn’t one there, or overwrites the text in the file if it exists with the two lines specified in the program.

File Management # PROGRAM FileWriter3 Message = ["line 1\n", "line 2\n", "line 3\n"] file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.writelines(Message)) file_pointer.close() # END.

File Management # PROGRAM FileWriter3 Message = ["line 1\n", "line 2\n", "line 3\n"] file_pointer = open("C:\Python34\MyData2.txt", "w") print(file_pointer.writelines(Message)) file_pointer.close() # END. This program opens a file called MyData2.txt for WRITing, and creates a new file if there isn’t one there, or overwrites the text in the file if it exists with the three lines specified in the program.

File Management # PROGRAM FileWriter4 Message = ["line 1\n", "line 2\n", "line 3\n"] file_pointer = open("C:\Python34\MyData2.txt", “a") print(file_pointer.writelines(Message)) file_pointer.close() # END.

File Management # PROGRAM FileWriter4 Message = ["line 1\n", "line 2\n", "line 3\n"] file_pointer = open("C:\Python34\MyData2.txt", “a") print(file_pointer.writelines(Message)) file_pointer.close() # END. Does the same as the previous program, except instead of overwriting the existing text in the file, it appends the new three lines into the file. Current File Message

File Management # PROGRAM FileWriter5 file_pointer = open("C:\Python34\MyData2.txt", "r+") Current_file = file_pointer.read() New_file = "Start of file\n" + Current_file file_pointer.seek(0) # This resets the pointer to the start file_pointer.write(New_file) file_pointer.close() # END.

File Management # PROGRAM FileWriter5 file_pointer = open("C:\Python34\MyData2.txt", "r+") Current_file = file_pointer.read() New_file = "Start of file\n" + Current_file file_pointer.seek(0) # This resets the pointer to the start file_pointer.write(New_file) file_pointer.close() # END. This adds the line “Start of file” to the start of the file. Current File Message

Reading Binary Files

File Management Let’s look at READing a BINARY file using the open() and the read() commands:

File Management # PROGRAM FileBinReader file_pointer = open("C:\Python34\Python.gif", "br") first4 = tuple(file_pointer.read(4)) if first4 == (0x47, 0x49, 0x46, 0x38): # THEN print("This is a GIF file") else: print("This is not a GIF file") # ENDIF; file_pointer.close() # END.

File Management # PROGRAM FileBinReader file_pointer = open("C:\Python34\Python.gif", "br") first4 = tuple(file_pointer.read(4)) if first4 == (0x47, 0x49, 0x46, 0x38): # THEN print("This is a GIF file") else: print("This is not a GIF file") # ENDIF; file_pointer.close() # END. This checks if the file specified is a GIF file or not. If it is a GIF it will start with HEX values 0x47, 0x49, 0x46, 0x38.

etc.