Friday 28 February 2014

File operations in Python



1.       File Open

Here is the basic function for opening a file
f = open(‘file’, ‘mode’)
there are multiple mode used in python
f is called file handler, that is the object we used to control the file in further.
Common mode in python:
  • a: append mode – append the content at the end of the file
  • w: write mode – write the content into the file, it will erase the original conent of the file
  • r: read mode – read the cotent from the file. The default mode.
  • r+ : read and write mode


2.       File Read

There are a few methods to read the content from a file
f.readline() – just read one line from the file, return a string
f.readlines() – read all lines and return a list containing all lines.
f.read([character number]) – read specific characters. Without parameter, it will read all the content. The read will move the reading pointer ahead. We can use f.tell() to get the current pointer position.

3.       File Write

When we need to write the content to the file, we need to open the file as write or append mode
f.write(“string”) – write some string into the file
f.writelines(string list) – write mulitple lines into the file

4.       File delete

We need to use the os module to delete the file in operation system. To avoid deleting non-existing file, we need to check if the file is there.
os.remove(‘file’) or os.unlink(‘file’)    #delete the file from os
Sample code:
import os
if os.path.exists(‘/var/tmp/file’) : os.remove (‘/var/tmp/file’)

5.       file copy/move

we need to use the shutil module to copy or move the file in between OS. To avoid the source file is already existing, we need to check the source file as well.
Sample code
import shutil
if os.path.exists(‘/var/tmp/file’) : shutil.copyfile(‘/var/tmp/file’,’/var/tmp/file1’)            #copy file
if os.path.exists(‘/var/tmp/file’) : shutil.move(‘/var/tmp/file’,’/var/tmp/file1’)         #move file

6.       directory relate operations

os.mkdir(“dirpath”, mode=)         #mkdir
os.makedirs(‘dirpath’, mode=)      #create directory when the parent directory is not existing
os.rmdir(‘directory’)                   #remove the directory
os.removedirs(‘directorytree’)             #remove the directory tree.
os.listdir(‘path’)                   #list the files and directories in the directory (the name is a little bit confusing)
os.walk() or os.path.walk()    # Traversal the directory.
os.walk()        will return a tuple, each element contains the path, subdirectories and files

7.       stdin, stdout, stderr

we can change the stdin, stdout, stderr in python by assign sys.[file] to other values
for example, we will change the stdout
>>> import sys
>>> sys.stdout=open(r"./hello.txt","a")        #change the stdout value
>>> print "good bye"                           # you won’t see the ‘good bye’ printed onto screen.
>>> sys.stdout.close()                         # it is in the hello.txt file



No comments:

Post a Comment