python學習筆記: 一些有用的文件操作函數

def read_file(filename):
    '''Tries to read a given file

    Returns None if an error is encountered
    '''
    encodings = ['utf-8']

    try:
        import chardet
    except ImportError:
        logging.info("chardet not found. 'utf-8' encoding will be assumed")
        chardet = None

    if False and chardet:
        with open(filename, 'rb') as file:
            content = file.read()
        guess = chardet.detect(content)
        logging.info('Chardet guesses %s for %s' % (guess, filename))
        encoding = guess.get('encoding')

        # chardet makes errors here sometimes
        if encoding in ['MacCyrillic', 'ISO-8859-7']:
            encoding = 'ISO-8859-2'

        if encoding:
            encodings.insert(0, encoding)

    # Only check the first encoding
    for encoding in encodings[:1]:
        try:
            # codecs.open returns a file object that can write unicode objects
            # and whose read() method also returns unicode objects
            # Internally we want to have unicode only
            with codecs.open(filename, 'rb', encoding=encoding, errors='replace') as file:
                data = file.read()
                return data
        except ValueError, err:
            logging.info(err)
        except Exception, e:
            logging.error(e)
    return ''

讀文件,主要是處理了不同平臺的不同編碼。。。

寫文件,創建文件,一些目錄操作。

def write_file(filename, content):
    assert os.path.isabs(filename)
    try:
        with codecs.open(filename, 'wb', errors='replace', encoding='utf-8') as file:
            file.write(content)
    except IOError, e:
        logging.error('Error while writing to "%s": %s' % (filename, e))


def make_directory(dir):
    if not os.path.isdir(dir):
        os.makedirs(dir)

def make_directories(dirs):
    for dir in dirs:
        make_directory(dir)

def make_file(file, content=''):
    if not os.path.isfile(file):
        write_file(file, content)

def make_files(file_content_pairs):
    for file, content in file_content_pairs:
        make_file(file, content)

def make_file_with_dir(file, content):
    dir = os.path.dirname(file)
    make_directory(dir)
    make_file(file, content)

得到相對路徑:(1,平臺問題,2,python版本問題)

def get_relative_path(from_dir, to_dir):
    '''
    Try getting the relative path from from_dir to to_dir
    The relpath method is only available in python >= 2.6
    if we run python <= 2.5, return the absolute path to to_dir
    '''
    if getattr(os.path, 'relpath', None):
        # If the data is saved on two different windows partitions,
        # return absolute path to to_dir
        drive1, tail = os.path.splitdrive(from_dir)
        drive2, tail = os.path.splitdrive(to_dir)

        # drive1 and drive2 are always empty strings on Unix
        if not drive1.upper() == drive2.upper():
            return to_dir

        return os.path.relpath(to_dir, from_dir)
    else:
        return to_dir

結果輸出:

python path_relpath.py 
From path: /home/nn/Study
To path: /home/nn/Work
DIR : ../Work

代碼選自rednotebook project.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章