python学习笔记: 一些有用的文件操作函数
2012-09-24 14:46
1066 查看
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.
相关文章推荐
- python学习笔记-day03 第四部分(函数和文件操作)
- python 系统学习笔记(八)---文件操作
- python学习笔记 操作文件和目录
- IPython下目录的操作-魔力函数(cd pwd bookmark dhist )- 千月的python linux 系统管理指南学习笔记(7)
- Python学习笔记015——文件file的常规操作之一(文本文件)
- Python学习笔记3:简单文件操作
- Python学习笔记——一些常用函数、常见错误总结
- Python学习笔记3:简单文件操作
- python的学习笔记之对文件、目录的操作
- Python的学习笔记14------操作文件和目录
- Python学习笔记(四)文件操作
- Python学习笔记之简单文件操作
- Python学习笔记(18)-目录操作与文件读写
- [置顶] Python联系笔记2[列表,元组,集合,字典,函数,文件操作,模块,类]
- Python学习笔记——文件对象和操作(1)
- python学习笔记4-python文件操作
- 学习笔记之Python 切片:利用切片操作,实现一个trim()函数,去除字符串首尾的空格
- python核心编程学习笔记-2016-08-02-01-读取文件的函数中的文件指针问题
- Python3学习笔记05-字典、文件输入输出、模块、函数参数传递
- Go学习笔记二: 函数,文件操作及网络通信