您的位置:首页 > 编程语言 > Python开发

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: