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])

Slides:



Advertisements
Similar presentations
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Advertisements

Introduction to Computing Using Python File I/O  File Input/Output  read(), readline(), readlines()  Writing to a file.
Computer Science 111 Fundamentals of Programming I Files.
CPS120: Introduction to Computer Science Lecture 15 B Data Files.
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Lists Introduction to Computing Science and Programming I.
Files in Python The Basics. Why use Files? Very small amounts of data – just hardcode them into the program A few pieces of data – ask the user to input.
Files in Python Input techniques. Input from a file The type of data you will get from a file is always string or a list of strings. There are two ways.
Working with Files CSC 161: The Art of Programming Prof. Henry Kautz 11/9/2009.
CS0007: Introduction to Computer Programming File IO and Recursion.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 17 Reading and Writing Files 5/10/09 Python Mini-Course: Lesson 17 1.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
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.
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.
18. PHP File Operations Opening a File
Course A201: Introduction to Programming 12/9/2010.
Files Victor Norman CS104. Reading Quiz, Q1 A file must be ___________ before a program can read data from it. A. accessed B. unlocked C. opened D. controlled.
STL List // constructing lists #include int main () { // constructors used in the same order as described above: std::list first; // empty list of ints.
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.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
CIT 590 Intro to Programming Files etc. Announcements From HW5 onwards (HW5, HW6,…) You can work alone. You can pick your own partner. You can also stick.
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.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?
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 ….
Python – May 12 Recap lab Chapter 2 –operators –Strings –Lists –Control structures.
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
Input and Output in python Josh DiCristo. How to output numbers str()  You can put any variable holding a number inside the parentheses and it will display.
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.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
CIT 590 Intro to Programming Files etc. Agenda Files Try catch except A module to read html off a remote website (only works sometimes)
Files A collection of related data treated as a unit. Two types Text
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.
Kanel Nang.  Two methods of formatting output ◦ Standard string slicing and concatenation operations ◦ str.format() method ie. >>> a = “The sum of 1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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()
Topic: File Input/Output (I/O)
06 File Objects and Directory Handling
File I/O File input/output Iterate through a file using for
File Writing Upsorn Praphamontripong CS 1110
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Python’s input and output
Ruth Anderson UW CSE 160 Winter 2016
Ruth Anderson UW CSE 160 Winter 2017
Ruth Anderson UW CSE 160 Spring 2018
File Handling Programming Guides.
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
Fundamentals of Programming I Files
File I/O File input/output Iterate through a file using for
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
File I/O File input/output Iterate through a file using for
Fundamentals of Data Structures
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
File Input and Output.
CS 1111 Introduction to Programming Fall 2018
Introduction to Python: Day Three
Python programming exercise
Files Handling In today’s lesson we will look at:
Topics Introduction to File Input and Output
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
File Input and Output.
Topics Introduction to File Input and Output
CS 1111 Introduction to Programming Spring 2019
Presentation transcript:

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]) f = open('/path/to/file', 'r') Once a file is opened and you have one file object, you can get various information related to that file.

Opens a file for reading only r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

Opens a file for both reading and writing r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.

Opens a file for writing only w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

Opens a file for both writing and reading w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

Opens a file for appending a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

Opens a file for both appending and reading a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Opens a file for both appending and reading in binary format ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

open a file that doesn’t exist If we try to open a file that doesn’t exist, we get an error: >>> mynewhandle = open("wharrah.txt", "r") IOError: [Errno 2] No such file or directory: "wharrah.txt"

list of attributes related to file object AttributeDescription file.closedReturns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.nameReturns name of the file.

close() When you are done reading from or writing to a file you can close() the file and free memory. f.close() After closing a file, attempts to access the file will fail.

Reading a file line-at-a-time The readline() method read one line of a file. readline() returns one line of the file as a string with a new line character ( '\n' ) at the end. If readline() returns an empty string, the end of the file has been reached.

readline() >>> f.readline() 'This is the first line.\n' >>> f.readline() 'This is the second line.\n' >>> f.readline() …

Reading a file line-at-a-time mynewhandle = open("test.txt", "r") while True: # Keep reading forever theline = mynewhandle.readline() # Try to read next line if len(theline) == 0: # If there are no more lines break # leave the loop # Now process the line we’ve just read print(theline, end="") mynewhandle.close()

readlines() readlines() methods read multiple lines of a file. readlines() returns all of the lines in a file as a list. Each line in the list will have a newline character ( '\n' ) at the end.

Turning a file into a list of lines readlines() returns all of the lines in a file as a list. Each line in the list will have a newline character ( '\n' ) at the end. >>> f.readlines() ['This is the first line\n', 'This is the second line\n']

Turning a file into a list of lines f = open("friends.txt", "r") xs = f.readlines() f.close() xs.sort() g = open("sortedfriends.txt", "w") for v in xs: g.write(v) g.close()

The read() method will return the contents of the file as a string. Be careful that your computer has enough memory to read the entire file at once. read() accepts an optional parameter called 'size' that restricts Python to reading a specific portion of the file. f.read() Reading the whole file at once

f = open("somefile.txt") content = f.read() f.close() words = content.split() print("There are {0} words in the file.".format(len(words))) Notice here that we left out the "r" mode in line 1. By default, if we don’t supply the mode,

write() method The write() method takes a string as input and writes it to a file. Other data types must be converted to strings before they can be written to a file. The write() method does not add a newline character ('\n') to the end of the string.

write() method >>> data = 'This string will now be written to a file.' >>> f.write(data) 42

Writing our first file

directory we’re assuming that the file somefile.txt is in the same directory as your Python source code. If this is not the case, you may need to provide a full or a relative path to the file. On Windows, a full path could look like "C:\\temp\\somefile.txt", while on a Unix system the full path could be "/home/jimmy/somefile.txt".

Working with binary files Files that hold photographs, videos, zip files, executable programs, etc. are called binary files: they’re not organized into lines, and cannot be opened with a normal text editor. Python works just as easily with binary files, but when we read from the file we’re going to get bytes backrather than a string.

Here we’ll copy one binary file to another: f = open("somefile.zip", "rb") g = open("thecopy.zip", "wb") while True: buf = f.read(1024) if len(buf) == 0: break g.write(buf) f.close() g.close()

Working with binary files we added a "b" to the mode to tell Python that the files are binary rather than text files. In line 5, we see read can take an argument which tells it how many bytes to attempt to read from the file. Here we chose to read and write up to 1024 bytes on each iteration of the loop. When we get back an empty buffer from our attempt to read, we know we can break out of the loop and close both the files. If we set a breakpoint at line 6, (or print type(buf) there) we’ll see that the type of buf is bytes.

write binary

Filter Program Many useful line-processing programs will read a text file line-at-a-time and do some minor processing as they write the lines to an output file. They might number the lines in the output file, or insert extra blank lines after every 60 lines to make it convenient for printing on sheets of paper, or extract some specific columns only from each line in the source file, or only print lines that contain a specific substring. We call this kind of program a filter.

A filter that copies one file to another 1 def filter(oldfile, newfile): 2 infile = open(oldfile, "r") 3 outfile = open(newfile, "w") 4 while True: 5 text = infile.readline() 6 if len(text) == 0: 7 break 8 if text[0] == "#": 9 continue # Put any more processing logic here 12 outfile.write(text) infile.close() 15 outfile.close()

Directories When we create a new file by opening it and writing, the new file goes in the current directory (wherever we were when we ran the program). Similarly, when we open a file for reading, Python looks for it in the current directory.

Directory If we want to open a file somewhere else, we have to specify the path to the file, which is the name of the directory (or folder) where the file is located: >>> wordsfile = open("c:/temp/words.txt", "r") >>> wordlist = wordsfile.readlines() >>> print(wordlist[:6]) [’\n’, ’A\n’, "A’s\n", ’AOL\n’, "AOL’s\n", ’Aachen\n’]