Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

Slides:



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

1 A Censor Class class Censor: def __ init __ badwords=[]): self.badwords = badwords self.replacers = replacers def input_badwords(self,fpath):
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
COMP234 Perl Printing Special Quotes File Handling.
Computer Science 111 Fundamentals of Programming I Files.
Alford Academy Business Education and Computing1 Advanced Higher Computing Based on Heriot-Watt University Scholar Materials File Handling.
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.
Tim Wentz Nathaniel Smith Andrew Johnson. Files in Java Create a new file handle using: ▫new File(String pathname); Pathnames can be either relative or.
Reading and Writing Files Keeping Data. Why do we use files? ä For permanently storing data. ä For dealing with information too large to fit in memory.
Topics This week: File input and output Python Programming, 2/e 1.
CS0007: Introduction to Computer Programming File IO and Recursion.
ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS Jehan-François Pâris
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
Course A201: Introduction to Programming 12/9/2010.
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.
Storing and Retrieving Data
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.
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING Jehan-François Pâris
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 ….
Querying Directory Contents Copyright © The University of Edinburgh 2011 This work is licensed under the Creative Commons Attribution License See
Python Let’s get started!.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
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])
Lecture 4 Python Basics Part 3.
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.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery.
Input, Output and Variables GCSE Computer Science – Python.
Topic: File Input/Output (I/O)
G. Pullaiah College of Engineering and Technology
Lesson 08: Files Class Participation: Class Chat: Attendance Code 
Python Let’s get started!.
Lecture 4 Python Basics Part 3.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
IST256 : Applications Programming for Information Systems
Binary Files.
Ruth Anderson UW CSE 160 Winter 2016
Exceptions and files Taken from notes by Dr. Neil Moore
Ruth Anderson UW CSE 160 Winter 2017
And now for something completely different . . .
Ruth Anderson UW CSE 160 Spring 2018
Topics Introduction to File Input and Output
Python’s Errors and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Lesson 08: Files Topic: Introduction to Programming, Zybook Ch 7, P4E Ch 7. Slides on website.
Fundamentals of Programming I Files
File Handling.
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
Using Text Files in Python
Lesson 08: Files Class Chat: Attendance: Participation
Reading and Writing Files
Advanced Python Concepts: Exceptions
15-110: Principles of Computing
Topics Introduction to File Input and Output
Advanced Python Concepts: Exceptions
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Presentation transcript:

Python – reading and writing files

??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?

To Write a file #written to C:\Users\jrw\workspace\Python1 file = open("newfile.txt", "w") file.write("Hello World \n") file.close()

#written to C:\Users\jrw\workspace\Python1 file = open("newfile2.txt", "w") file.write("Hello") file.write("World") file.close() #writes HelloWorld Note: you need to include “\n” for newline.

“””triple quotes””” file = open("newfile3.txt", "w") file.write(""" Hello Again""") file.close() #will write the following Hello Again

What does this write? #written to C:\Users\jrw\workspace\Python1 file = open("newfile4.txt", "w") file.write("Hello") file.close() file = open("newfile4.txt", "w") file.write("Again") file.close()

What does this write? #written to C:\Users\jrw\workspace\Python1 file = open("newfile5.txt", "w") file.write("Hello") file.write("Again") file.close()

Printing to a file file = open("newfile5.txt", "w") print >> file, "START OF FILE" print >> file, "END OF FILE" del file #this will print directly to a file #del file deletes the file object and allows contents to be written to file.

Appending a File with open("test.txt", "a") as myfile: myfile.write("appended text")

Reading a line of a File input1 = file("newfile5.txt", "r") print input1.readline() #this will also read the “\n” at the end of line

Read a file input1 = file("newfile5.txt", "r") print input1.read() #this will read the remainder of a file

Reads a file into a list with open("newfile5.txt") as f: contents = f.readlines() for content in contents: print content ??? Read a file into an array. ??? Number of lines in a file

Iterate through a file (line by line) input1 = file("newfile5.txt", "r") for line in input1.readlines(): print str(len(line)) + " " + line #adds the length of a line to the start of each line

File Exceptions A file or directory (path) does not exist. You do not have read/write permissions Disk error try: fh = open("output/testfile1.txt", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close()

Enter A Number while True: try: x = int(raw_input("Please enter a number: ")) break except ValueError: print "Oops! That was no valid number. Try again" print "you entered" + str(x)

Path - join import os.path filePath = os.path.join("output", "file1.txt") #output\file1.txt fh = open(filePath, "w") fh.write("in file output\file1.txt on Windows machine")

Path - split import os.path filePath = os.path.split("output/file1.txt") (pathName, fileName) = filePath print pathName # output print fileName # file1.txt

Path – split recursively import os.path def split_fully(path): parent_path, name = os.path.split(path) if name == "": return (parent_path, ) else: return split_fully(parent_path) + (name, ) split_fully("dir1/dir2/file1.txt") #('', 'dir1', 'dir2', 'file1.txt')

Splitting file extensions import os.path print os.path.splitext("file.txt") #('file', '.txt')

If a path exists print os.path.exists("C:\Users\jrw\file. txt") #returns true or false