2013-07-14 123 views
0

我已經做了一個程序,收集和創建配置文件(.ini)內的數據,但事情是我需要知道我可以做到這一點,所以它會檢查配置文件中是否有東西,那麼如果它不在那裏,它會把它放到那裏。Python:檢查配置文件

這裏是什麼樣的,我希望它看起來像:

if 'name' not in config: 
    config['name'] 
else: 
    print('Name already exists.') 

所以任何想法?

在此先感謝!

+0

這與tkinter有什麼關係? –

回答

0

這裏有一個例子:

import os 

# File does not exist, let's create it 
if os.path.exists('name') == False: 
    f = open('name', 'w') 
    f.write('sometext') 
    f.close() 

# File exists, let's check if it's empty and write into it 
# or if there's some text, write nothing 
else: 
    f = open('name', 'rw') 
    prev_text = f.read() 

    # File was empty 
    if prev_text == '': 
     f.write('sometext') 
    # File already had some text 
    else: 
     print 'This name already exists' 

    f.close() 
0

嗯,我做這個固定:

if user in config: 
    print('User Taken!') 
else: 
config.add_section(user) 

這整理了這一切,但感謝您的幫助反正!