Python file Exercises

Source: Internet
Author: User

Practice content:

Use Python to manage INI files: Implement queries, add, delete, save operations.

Practice Purpose:

1. Master the basic operation of the file

2. Recognize the INI file

3. Understand Configparser;

INI configuration file format:

Section: [Session]

Parameter (key = value)

[Port]

port1=3306

Import Configparser

Cfg=configparser.configparser ()

Vim Test.txt

[UserInfo]

Name=nyan

Pwd=password

[Study]

Python_base=15

Python_junior=30

Linux_base=15


Cfg.read (' Test.txt ')

Cfg.sections ()

Cfg.items

For SE in cfg.sections ():

Print SE

Print Cfg.items (SE)

Cfg.set (' userinfo ', ' pwd ', ' passw0rd '): Modify

Cfg.set (' userinfo ', ' email ', ' [email protected] '): Insert

Cfg.remove_option (' userinfo ', ' email ')

inimanage.py

Import OS

Import Os.path

Import Confugparser

...

1.dump INI

2.del section

3.del Item

4.modify Item

5.add section

6.save Modify

...

Class Student_info (object):

def __init__ (self.recordfile):

Self.logfile = Recordfile

Self.cfg = Configparser.configparser ()

def cfg_load (self):

Self.cfg.read (Self.logfile)

def cfg_dump (self):

Se_list = Self.cfg.sections ()

Print "================="

For SE in se_list:

Print SE

Print Self.cfg.items (SE)

Print "================="

def delete_item (Self,section,key):

Self.cfg.remove_option (Setion,key)

def delete_section (self, section):

Self.cfg.remove_section (section)

def add_section (self,section):

Self.cfg.add_section (section)

def set_item (Self,section,key,value):

Self.cfg.set (Section,key,value)

def save (self):

fp = Oopen (' Test.txt ', ' W ')

Self.cfg.write (FP)

Dp.close ()

if __name__ = = ' __main__ ':

info = student_info (' test.txt ')

Info.cfg_load ()

Info.cfg_dump ()

Info.set_item (' userinfo ', ' pwd ', ' passw0rd ')

Info.cfg_dump ()

Info.add_section (' login ')

Info.set_item (' login ', ' 2015-0511 ', ' 20 ')

Info.cfg_dump ()

Info.save ()

  

Python file Exercises

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.