我是Python中的菜鸟
问题:查找并替换文件中的键(字符串)
为此,我使用的是Python ConfigParser。但我想立即将整个配置(.ini)文件读入字典而不管各个部分。
我不想一次阅读一个部分
dict(Config.items('Section'))
不想遍历各个部分
for each_section in conf.sections():
for (each_key, each_val) in conf.items(each_section):
print each_key
print each_val
我还有哪些其他选择?
------- 编辑1 -------
的Config.ini
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
下面是包含要重新定位的键的文件
my dir is home_dir
my lib dir is library_dir
python path is path
My pictures are placed at my_pictures
答案 0 :(得分:0)
如果你想要一个字典,将配置文件中的所有值作为键值对而不管其部分,我认为你的方法是正确的
dict={}
for sec in config.sections():
for item in config.items(sec):
dict[item[0]]=item[1]
答案 1 :(得分:0)
我认为您仅限于阅读不同的部分,以获取每个部分中每个选项的不同值。
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawer;
protected FrameLayout frames;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
@Override
public void onBackPressed() {
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
@Override
public void setContentView(int layoutResID) {
// Set the base layout
super.setContentView(R.layout.activity_home);
// Find the content container
frames = findViewById(R.id.main_container);
// Inflate the extending Activity's layout into it
getLayoutInflater().inflate(layoutResID, frames);
// The rest of the base setup
Toolbar toolbar = findViewById(R.id.custom_tool);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
}
我认为它的可读性较差,但是您可以简化为:
dict_sectionValues = {}
for section in Config.sections():
for option in Config.options(section):
value = Config.get(section, option)
dict_sectionValues[option] = value