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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值