乐趣区

关于python:python3配置文件的读取与文件夹的拷贝

配置文件的读取要点

python 反对读取.ini 和.conf 结尾的配置文件,将配置文件放在内部有利于后续批改。在读取配置文件时通常应用相对路径,这时要先获取以后文件所在文件夹的绝对路径,应用如下代码能够取得:

path = os.path.dirname(__file__)

如果要获取以后文件的相对路径则将 dirname 改为 abspath 即可。
以下为读取配置文件残缺代码:

import configparser
import os
import shutil

#创立配置文件读取对象
cf = configparser.ConfigParser()
#获取以后文件夹绝对路径
path = os.path.dirname(__file__)
print(path)
#加载配置文件
cf.read(path + "/config.ini")

configparser在对文件进行后续操作之前须要调用 read() 办法先进行读取,须要留神。
配置文件格式如下:

[filePath]
sourcePath = E:/testCopyFile/sourceDir
destPath = E:/testCopyFile/destDir/

配置文件中须要留神的是字符串类型的配置不须要加引号。

拷贝局部

python 中有 shutil 包来反对文件操作。拷贝文件夹应用办法 copytree()来实现,须要留神的是当指标文件夹存在时拷贝会失败报错,此时须要批改源码来防止这个问题(shutil.py 源码):

def _copytree(entries, src, dst, symlinks, ignore, copy_function,
              ignore_dangling_symlinks, dirs_exist_ok=False):
    if ignore is not None:
        ignored_names = ignore(os.fspath(src), [x.name for x in entries])
    else:
        ignored_names = set()
    #此处本来没有判断文件夹不存在的判断,这里判断一下当文件夹不存在时创立文件夹防止间接创立可能导致的报错
    if not os.path.exists(dst):
        os.makedirs(dst, exist_ok=dirs_exist_ok)
    errors = []
    use_srcentry = copy_function is copy2 or copy_function is copy

    for srcentry in entries:
        if srcentry.name in ignored_names:
            continue
        srcname = os.path.join(src, srcentry.name)
        dstname = os.path.join(dst, srcentry.name)
        srcobj = srcentry if use_srcentry else srcname
        try:
            is_symlink = srcentry.is_symlink()
            if is_symlink and os.name == 'nt':
                # Special check for directory junctions, which appear as
                # symlinks but we want to recurse.
                lstat = srcentry.stat(follow_symlinks=False)
                if lstat.st_reparse_tag == stat.IO_REPARSE_TAG_MOUNT_POINT:
                    is_symlink = False
            if is_symlink:
                linkto = os.readlink(srcname)
                if symlinks:
                    # We can't just leave it to `copy_function` because legacy
                    # code with a custom `copy_function` may rely on copytree
                    # doing the right thing.
                    os.symlink(linkto, dstname)
                    copystat(srcobj, dstname, follow_symlinks=not symlinks)
                else:
                    # ignore dangling symlink if the flag is on
                    if not os.path.exists(linkto) and ignore_dangling_symlinks:
                        continue
                    # otherwise let the copy occur. copy2 will raise an error
                    if srcentry.is_dir():
                        copytree(srcobj, dstname, symlinks, ignore,
                                 copy_function, dirs_exist_ok=dirs_exist_ok)
                    else:
                        copy_function(srcobj, dstname)
            elif srcentry.is_dir():
                copytree(srcobj, dstname, symlinks, ignore, copy_function,
                         dirs_exist_ok=dirs_exist_ok)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy_function(srcobj, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error as err:
            errors.extend(err.args[0])
        except OSError as why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError as why:
        # Copying file access times may fail on Windows
        if getattr(why, 'winerror', None) is None:
            errors.append((src, dst, str(why)))
    if errors:
        raise Error(errors)
    return dst

还有一点是在指标文件夹中不会创立源文件夹,也就是说这个办法相当于是将源文件夹中的所有内容拷贝到指标文件夹中,因为我须要指标文件夹中存在源文件夹所以要独自创立:

sourcePath = cf.get('filePath', 'sourcePath')
destRootPath = cf.get('filePath', 'destPath')
destCopyPath = destRootPath + '/sourcePath'

if not os.path.exists(destCopyPath):
    os.makedirs(destCopyPath)
shutil.copytree(sourcePath, destCopyPath)
退出移动版