Python File Handling. Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations.

Slides:



Advertisements
Similar presentations
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.
Advertisements

BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
Computer Science 111 Fundamentals of Programming I Files.
J. Michael Moore Text Files CSCE 110 From James Tam’s material.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
Slide 1 Introduction To Files In Python In this section of notes you will learn how to read from and write to text files.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in your Pascal programs.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 11: 1 CMT1000: Introduction to Programming Ed Currie Lecture 10: File Input.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
James Tam Introduction To Files In Pascal You will learn how to read from and write to text files in Pascal.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
Lecture 16 – Open, read, write and close files.  At the end of this lecture, students should be able to:  understand file structure  open and close.
AI/ES (Artificial Intelligence / Expert System) Visual Prolog: Part Fall. SME., Pukyong Nat ’ l Univ. Kim, Minsoo.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Linux Operations and Administration
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Computer Programming TCP1224 Chapter 13 Sequential File Access.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
LECTURE 4 Files, File open, Read, Write. File Upload - In this lecture we will teach you how to open, read, and close a file on the server. - PHP Open.
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,
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
File Handling in QBASIC
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Introduction to Files in VB Chapter 9.1, 9.3. Overview u Data Files  random access  sequential u Working with sequential files  open, read, write,
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
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])
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
Lecture 4 Python Basics Part 3.
Learners Support Publications Working with Files.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Files A collection of related data treated as a unit. Two types Text
James Tam Introduction To Files In Python In this section of notes you will learn how to read from and write to files in your programs.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
IIITD File Input / Output In Python. File and operations  File is a named location on disk to store related information  When we want to read from or.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Introduction To Files In Python
Topic: File Input/Output (I/O)
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Plan for the Day: I/O (beyond scanf and printf)
Starting Out with Programming Logic & Design
Files I/O, Streams, I/O Redirection, Reading with fscanf
Imperative Programming
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Introduction To Files In Python
Fundamentals of Programming I Files
File Handling.
File Handling.
Introduction To Files In Python
Reading and Writing Files
Files.
Topics Introduction to File Input and Output
Introduction to Programming with Python
Reading Data From and Writing Data To Text Files
Topics Introduction to File Input and Output
EECE.2160 ECE Application Programming
Imperative Programming
Presentation transcript:

Python File Handling

Python language provides numerous built-in functions Some of the functions widely used for standard input and output operations – input() – raw_input() – print()

File I/O Operations To read from or write to a file – Open a file – Read or write (perform operation) – Close the file

File Open Operation Python has a built-in function to open a file. open() It returns a file object, also called a handle, as it is used to read or modify the file accordingly. # open file in current directory >>> f = open("test.txt") # specifying full path >>> f = open("C:/Python33/README.txt")

Opening Files Prepares the file for reading A.Links the file variable with the physical file (references to the file variable are references to the physical file). B.Positions the file pointer at the start of the file. Format: 1 = open(, "r") Example: ( Constant file name) inputFile = open("data.txt", "r") OR (Variable file name: entered by user at runtime) fname = input("Enter name of input file: ") inputFile = open(fname, "r") 1 Examples assume that the file is in the same directory/folder as the Python program.

Python File Modes ModeDescription ‘r’Open a file for reading ‘w’Open a file for writing, Creates a new file if it does not exist or truncates the file if it exists ‘x’Open a file for exclusive creation. If the file already exists, the operation fails 'a'Open for appending at the end of the file without truncating it. Creates a new file if it does not exist 't‘Open in text mode 'b‘Open in binary mode ‘+’'+'Open a file for updating (reading and writing)

Opening Files in different Modes # equivalent to 'r' or 'rt' f = open("test.txt") # write in text mode f = open("test.txt",'w') # read and write in binary mode f = open("img.bmp",'r+b') # working with files in text mode with encoding type f = open("test.txt", mode = ‘r’,encoding = 'utf-8')

Reading Information From Files Typically reading is done within the body of a loop Each execution of the loop will read a line from the file into a string Format: for in : Example: for line in inputFile: # Echo file contents back onscreen print(line)

File Close Operation close() method on a file will free up the resources that were tied with the file. Python has a garbage collector to clean up unreferenced objects. What if the program encounters a runtime error and crashes before it reaches the end? The input file may remain ‘locked’ an inaccessible state because it’s still open. Format:.close() Example: inputFile.close() f = open("test.txt",encoding = 'utf-8') # perform file operations f.close()

Reading From Files: Putting It All Together inputFileName = input("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") for line in inputFile: sys.stdout.write(line) inputFile.close() print("Completed reading of file", inputFileName)

What You Need To Write Information To A File 1.Open the file and associate the file with a file variable (file is “locked” for writing). 2.A command to write the information. 3.A command to close the file.

Opening the File Format 1 : = open(, "w") Example: (Constant file name) outputFile = open("gpa.txt", "w") (Variable file name: entered by user at runtime) outputFileName = input("Enter the name of the output file to record the GPA's to: ") outputFile = open(outputFileName, "w") 1 Typically the file is created in the same directory/folder as the Python program.

Writing to a File Use the write() function in conjunction with a file variable. Format: outputFile.write(temp) Example: # Assume that temp contains a string of characters. outputFile.write (temp)

Writing To A File: Putting It All Together inputFileName = input("Enter the name of input file to read : ") outputFileName = input("Enter the name of the output file to record : ") inputFile = open(inputFileName, "r") outputFile = open(outputFileName, "w") print("Opening file", inputFileName, " for reading.") print("Opening file", outputFileName, " for writing.") gpa = 0

Writing To A File: Putting It All Together (2) for line in inputFile: if (line[0] == "A"): gpa = 4 elif (line[0] == "B"): gpa = 3 elif (line[0] == "C"): gpa = 2 elif (line[0] == "D"): gpa = 1 elif (line[0] == "F"): gpa = 0 else: gpa = -1 temp = str (gpa) temp = temp + '\n' print (line[0], '\t', gpa) outputFile.write (temp) inputFile.close () outputFile.close () print ("Completed reading of file", inputFileName) print ("Completed writing to file", outputFileName)

File Input: Alternate Implementation inputFileName = input ("Enter name of input file: ") inputFile = open(inputFileName, "r") print("Opening file", inputFileName, " for reading.") line = inputFile.readline() while (line != ""): sys.stdout.write(line) line = inputFile.readline() inputFile.close() print("Completed reading of file", inputFileName)

Data Processing: Files Files can be used to store complex data given that there exists a predefined format. Format of the example input file: ‘ employees.txt ’,,

Example Program: data_processing.py inputFile = open ("employees.txt", "r") print ("Reading from file input.txt") for line in inputFile: name,job,income = line.split(',') last,first = name.split() income = int(income) income = income + (income * BONUS) print("Name: %s, %s\t\t\tJob: %s\t\tIncome $%.2f" %(first,last,job,income)) print ("Completed reading of file input.txt") inputFile.close() # EMPLOYEES.TXT Adama Lee,CAG,30000 Morris Heather,Heroine,0 Lee Bruce,JKD master,100000