
|
Lesson 12 Notes: Working with Files
- Introduction
- Python can be used to create programs that manipulate the files on a computer.
- The os module contains functions for searching, listing, renaming, and deleting files.
- The os.path module contains a few specialized functions for manipulating files
- A number of functions for opening, reading, and writing to files are built into Python
- OS Functions: Just Looking
getcwd()
- "get current working directory"
- Returns the name of the current directory
listdir(path)
- Returns a list of all files in a directory
chdir(path)
- "change directory"
- Move focus to a different directory
- OS Functions: Adding
mkdir(path)
- "make directory"
- Make a new directory with the given name
makedirs(path)
- "make directories"
- Makes a subdirectory and all required parent directories
- Ex. makedirs("c:\\Python\newfiles\trash")
- OS Functions: Removing
remove(path)
rmdir(path)
- "remove directory"
- Deletes an empty directory
removedirs(path)
- Deletes a directory and everything in it
- OS Functions: Changing
rename(old,new)
- Change the name of a file from "old" to "new"
renames(old,new)
- Change name of file from old to new, changing directory names as needed
- os.path Functions: What is it?
exists(file)
isdir(path)
isfile(file)
- Sample Code: Erase All
import os, os.path
path = raw_input("folder to clean:")
os.chdir(path)
files = os.listdir(path)
print files
for file in files:
if os.path.isfile(file):
os.remove(file)
print "erased", file
elif os.path.isdir(file):
os.removedirs(file)
print "removed", file
else:
pass
- Openin' A File
open(filename, mode)
- Modes (must be in quotes)
- r = read
- w = write (replaces exisiting data)
- a = append (add to the end)
- To be able to use opened file, give it a variable handle.
- Example: openfile = open("filename.txt", "a")
- Readin' a File
file.read()
- Read whole file as a string
file.readline()
- Read a single line in as a string
file.readlines()
- Read whole file, each line becomes string item in a list.
- Writin' To a File
file.write(string)
- Write "string" to the file. How it is written will depend on mode the file is opened in.
file.writelines(list)
- Write all the string items in a list to the file.
- Each element in list will be on same line unless the element contains a newline character.
- Closin' Up
- Temp Files
- Functions in tempfile module can be used to create and handle temporary files.
tempfile.maketmp() creates a temporary file that has a random, unused name. The tempfile is located in the default temporary folder.
- Sample Read/Write Script
#Program to replace an old word with a new one
import string, tempfile, os
# Ask User for Information
filename = raw_input("Name of file: ")
find = raw_input("Search for: ")
replace = raw_input("Replace with: ")
#Open user file, read it, and close it
file = open(filename, "r")
text = file.readlines()
file.close()
#Edit information from user file
newtext =[]
for item in text:
line = string.replace(item, find, replace)
newtext.append(line)
#Create new file
newname=filename+".new"
newfile = open(newname, "w")
newfile.writelines(newtext)
newfile.close()
#Change names of files
oldfile=filename+".bak"
os.rename(filename, oldfile)
os.rename(newname, filename)
os.remove(oldfile)
- Exceptions
try and except can be used to catch errors in code.
try runs some commands or functions.
- If a function fails or returns an error, the
except commands are then run
- Can be used to handle program killing crashes very nicely.
- Sample Try / Except
def open_file():
filename = raw_input("Enter File Name: ")
try:
file = open(filename)
except:
print "File not found."
open_file()
return file
- Review
- What modules contain functions to manipulate files?
- What are the different modes for opening a file?
- What is the difference between readline() and readlines()? write(string) and writelines(list)?
- Why would you use a try / except construction?
Restricted access |