Pages

Tuesday, October 21, 2014

Python: check if file or directory exists








  • os.path.exists to check if file or directory exists.
    import os
    os.path.exists('/tmp/1.txt')
    os.path.exists('/tmp')
    
  • os.path.isfile to check if file exists.
    import os
    os.path.isfile('/tmp/1.txt')
    



Python: Get file absolute path








Use os.path.abspath function:
import os
os.path.abspath('abc/abc.txt')



Python: get the index of a char in a string








find and index method are available. The difference is that find returns -1 when what you're looking for isn't found, index throws an exception.
s='abc'
print(s.index('b')) # 1
print(s.find('b'))  # 1
print(s.find('d'))  # -1
print(s.index('d')) # exception



Python: string types in 2.x and 3.x








  • In Python 2.x, basestring is the base class for both str and unicode, while types.StringType is str. If you want to check if something is a string, use basestring. If you want to check if something is a ascii (bytestring), use str and forget about types.
  • Since Python 3.x, types not longer has StringType; str is always unicode. basestring no longer exists.



python: return inside with block








if returns value inside with statement, will the file be closed eventually?
The answer is YES
with open('myfile.txt') as f:
    return [line for line in f if len(line)>80]



Tuesday, October 14, 2014

python: iterables and iterators








A class with __iter__() method or __getitem__() method is iterable. The __iter__() method returns an iterator. A iterator object has a next() method (or __next__() method in python 3.0).
class Iterator(object):
    def next(self):
        pass

class Iterable(object):
    def __iter__(self):
        return Iterator()

see also




python: len() function and __len__() method








len is a function to get the length of a collection. It works by calling an object's __len__ method.
class AClass(object):
    def __init__(self):
        self._list = [1,2,3]

    def __len__(self):
        return len(self._list)

a=AClass()
print(a.__len__()) # 3
print(len(a))      # 3



python: call another static method








class AClass(object):
    def __init__(self):
        pass

    @staticmethod
    def a():
        AClass.b()

    @staticmethod
    def b():
        pass

see also