Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Python:unzip files

import zipfile
doczip = zipfile.ZipFile('c:/dcc.zip')
doczip.printdir()
for fileName in doczip.fileNamelist():
    print '%s: %r' % (fileName, docz

Python: Reading from a File

#open the file
text_file = open("fac.txt", "w")
# read from it
print text_file .read()
#close it
text_file .close()

Python: Splitting files Paths

import os, time
path= 'c:/test.txt'
print os.path.basename(path)       #test.txt
print os.path.dirname(path)        # C:
print os.path.split(p

Python: Listing Directories

import os
disk = "c:/"
print os.listdir(disk)
print [f for f in os.listdir(disk) if os.path.isfile(os.path.join(disk, f))]   [3]
print [f for

Python: read ZIP files

import zipfile
doczip = zipfile.ZipFile('c:/dcc.zip')
doczip.printdir()
# list zip file content
for name in doczip.namelist():
    print '%s: %r' %

Python: return the file’s attributes

import os, time
file= 'c:/test.txt'
# File size in bytes
print os.path.getsize(file)
# this function returns the time when the file was last access

Python: rename a file

import os
oldName = "c:/Here.mp3"
newName = "c:/Here2.mp3"
# delete the file if it exists
if os.access(newName, os.X_OK):
    print "deleting " + n

Python: Check if the file is closed

f = open("c:/Here.mp3", "rb")
print f.closed    # False
f.close()         # close the file
print f.name
print f.closed     #true

Python: collecting the names of all entries in a directory files whose names match a given filename pattern

import glob
#List python files
print glob.glob('*.py')
print glob.glob("?m*.py")

Python: Read and return one line from a file

import sys
def open_file(file, mode):
    try: 
        strm = open(file, mode)
    except(IOError), err:
        print "Unable to open the file '"

Python: delete a file

import os
os.remove("c:/test.txt")

Python: How to Use seek() to move file pointer

import os
 # Returns TRue when path names an existing file or directory
print os.path.exists('c:/test.txt')
 # Returns true when path names an exis

Python: read n characters from the file

file = open(r'c:/test.txt')
# Read the first 7 characters of the file
print file.read(7)
# Read the following 10 characters
print file.read(10)
# c

Python: return the current file position as the number of characters (bytes)

f = open(r"c:/test.txt")
print f.tell()                   #results: 0
print f.read(5)
# get current position
print f.tell()                    #res

Python: Read a file character by character

file = open('c:/test.txt', 'r')
while 1:
    char = file.read(1)          # read characters from file
    if not char: break
    print char,
# clos