configparser.configparser()从多个文件读取节()

2024-03-28 17:13:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的示例文件:

文件01

[sectionf1]
Keyf1=Valf1

文件02

^{pr2}$

文件03

[sectionf3]
Keyf3=Valf3

[sectionf31]
Keyf31=Valf31

文件04

[sectionf4]
Keyf4=Valf4

代码(Python3.2,Debian Wheezy 7.9):

import sys, os, shutil, configparser, datetime, re

cfgpars = configparser.ConfigParser()
cfgpars.optionxform = str
cfgpars._interpolation = configparser.ExtendedInterpolation()

#============ Handle the Python Path ===========#


pathname = os.path.dirname(sys.argv[0])
CDay= str(datetime.date.fromordinal(datetime.date.today().toordinal()))

PathFiles = os.path.abspath(pathname) + "/rbackup-files/"

dirs = os.listdir( PathFiles )

for File in dirs:
    cfgpars.read(PathFiles + File)
    print("\nRead file : " + File + "...")
    print (cfgpars.sections() )

print("\nDone !")

我的输出:

Read file : file01.ini...
['sectionf1']

Read file : file02.ini...
['sectionf1', 'sectionf2']

Read file : file03.ini...
['sectionf1', 'sectionf2', 'sectionf3', 'sectionf31']

Read file : file04.ini...
['sectionf1', 'sectionf2', 'sectionf3', 'sectionf31', 'sectionf4']

Done !

怎么了?我不明白为什么cfgpars.sections()添加了所有部分。在

通过http://httk.openmaterialsdb.se/_modules/httk/task/reader.html找到了soluce

for FileR in dirs:
    FilePath= PathFiles+FileR
    print("\nRead file : " + FileR + "..." + FilePath)
    cfgpars = configparser.ConfigParser()
    cfgpars.optionxform = str
    cfgpars._interpolation = configparser.ExtendedInterpolation()
    cfgpars.read([FilePath])
    print (cfgpars.sections() )

这是一首短篇短文。你可以试试这个小玩意儿。嘉顿·l’esprit ouvert et soyons Bienvelants envers ceux qui cherchent(…)

感谢那些认为stackoverflow不是教程的人。试试这个小的就好了。保持开放的心态,善待那些寻求帮助的人


Tags: 文件readdatetimeosiniconfigparserfileprint