Python Tutorial

Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Wednesday, May 15, 2013

Shutil: high level file operations

The shutil module provides a number of high-level operations on files and collections of files.

import shutil
import os

# copy(& rename) file from src to dst.
src = os.getcwd()+"\\"+"a.txt"
dst = os.getcwd()+"\\"+"data\\new_a.txt"
shutil.copyfile(src, dst)

# copy file from src to dst directory.
src = os.getcwd()+"\\"+"a.txt"
dst = os.getcwd()+"\\data2"
shutil.copy(src, dst)

'''
    Recursively copy an entire directory tree rooted at src.
    dst file must not exists 
'''    
src = os.getcwd()+"\\" + "data"
dst = os.getcwd()+"\\" + "data3"
shutil.copytree(src, dst)

# Recursively move a file or directory to another location.
src = os.getcwd()+"\\" + "data3"
dst = os.getcwd()+"\\" + "data4"
shutil.move(src, dst)

# delete entire directory
dest_file = os.getcwd()+"\\data3"
shutil.rmtree(dst)

Monday, February 18, 2013

File read code snippet



All source code available on github

import sys

def readFile(filename):
    try:
        file = open(filename,'r')
        content = file.read()
        file.close()
        return content
    except IOError:
        print "IOError:",IOError.args[0]
    except :
        print "Unexpected error:",sys.exc_info()[0]
        raise

Thursday, June 7, 2012

Access shared resource

Sometime we need to access shared document, for example when our application write to a single file on multi-thread. In this case we need to access the through locking.

This technique is useful for web crawler.
lock=threading.Lock()
def writeToFile():
    lock.acquire()
    try:
        //write data
    finally:
        lock.release()

Friday, August 20, 2010

python get all files of desired type from a directory

'''
   This code use for get all files of desired type from a directory
'''
import os

directory="C:/inputFolder/"
fileType=".doc"
files=[]
files=os.listdir(directory)
fileCounter=0
for fileName in files:
    if fileName.endswith(fileType):
        fileCounter=fileCounter+1
        print fileName
if fileCounter==0:
    print "No doc file found at ",directory

python remove/delete file or folder

'''
   This code use for remove a file/folder
'''
import os
import sys
import shutil

def deleteFileOrFolder(directory):
    if os.path.exists(directory):
        try:
            if os.path.isdir(directory):
                # delete folder
                shutil.rmtree(directory)
            else:
                # delete file
                os.remove(directory)
        except:
            print "Ecxeption ",str(sys.exc_info())
    else:
        print "not found ",directory

'''
   Function call
'''
#directory="C:/pythonFile.txt"
directory="C:/inputFolder/"
directory=deleteFileOrFolder(directory)





Output:
Check current directory

python remove/delete file

'''
   This code use for remove a file
'''
import os
import sys

directory="C:/pythonInputFile.doc"
if os.path.exists(directory):
    try:
        os.remove(directory)
    except:
        print "Exception: ",str(sys.exc_info())
else:
    print 'File not found at ',directory




Output:
Check current directory

python rename a file

'''
   This code use for rename a file
      - also change the file format
      - example of exception handling
'''
import os
import sys

currentDirectory="C:/pythonFile.txt"
if os.path.exists(fileDirectory):
    try:
        newFileName="pythonInputFile.doc"
        newDirectory=fileDirectory[0:fileDirectory.rfind("/")+1]+newFileName
        print newDirectory
        os.rename(currentDirectory,newDirectory)
    except:
        print "Exception: ",str(sys.exc_info())
else:
    print "File Not found"





Output:
Check current directory folder

Thursday, August 19, 2010

python file seek

'''
   This code use python file syntax
'''
'''
   Read data from file seek position
        pointer seek n'th byte, then start read data
'''
directory="C:/pythonFile.txt"
n=10
f=open(directory,'r')
f.seek(n)
for line in f.readlines():
    print line
f.close()




Output:



python file operation

'''
   This code use python file read/write syntax
'''

directory="C:/pythonFile.txt"

'''
   Open file in write mode
'''
f=open(directory,'w')
f.write("Life is easy with Python")
f.close()

'''
   Open file for writeing data in binary format
'''
f=open(directory,'wb')
f.write("Life is easy with Python")
f.close()


'''
   Open file in append mode
'''
f=open(directory,'a')
f.write("Life is easy with Python")
f.close()


'''
   Read data from file
'''
f=open(directory,'r')
for line in f.readlines():
    print line
f.close()






Output:

Check "C:" drive