Skip to content

3. 基础知识

  

3.1. 一个 Python 程序的示例

下面是一个演示 Python 基本功能的程序。


该程序(bases_01)

#    -*- coding=utf-8 -*-

# ----------------------------------
def affiche(chaine):
    #    chain poster
    print "chaine=%s" % (chaine)


# ----------------------------------
def afficheType(variable):
    #    displays variable type
    print "type[%s]=%s" % (variable,type(variable))

# ----------------------------------
def f1(param):
    #    add 10 to param
    return param+10

# ----------------------------------
def f2():
    #  returns 3 values
    return ("un",0,100);


#    -------------------------------- main program ------------------------------------
#  this is a comment
#    variable used without being declared
nom="dupont"

#    a screen display
print "nom=%s" % (nom)

#  a list with elements of different types
liste=["un","deux",3,4]

#  its number of elements
n=len(liste)

#    a loop
for i in range(n):
  print "liste[%d]=%s" % (i,liste[i])

#  initialize 2 variables with a tuple
(chaine1,chaine2)=("chaine1","chaine2")

#  concatenation of the 2 strings
chaine3=chaine1+chaine2

#    result display
print "[%s,%s,%s]" % (chaine1,chaine2,chaine3)

#  use function
affiche(chaine1)

#  the type of a variable can be known
afficheType(n)
afficheType(chaine1)
afficheType(liste)

#  the type of a variable can change at runtime
n="a change"
afficheType(n)

#    a function can return a result
res1=f1(4)
print "res1=%s" % (res1)

#  a function can return a list of values
(res1,res2,res3)=f2()
print "(res1,res2,res3)=[%s,%s,%s]" % (res1,res2,res3)

#  we could have retrieved these values in a
liste=f2()
for i in range(len(liste)):
    print "liste[%s]=%s" % (i, liste[i])

#    testing
for i in range(len(liste)):
    #    displays only channels
    if (type(liste[i])=="str"):
        print "liste[%s]=%s" % (i,liste[i])

#    other tests
for i in range(len(liste)):
    #    displays only integers >10
    if (type(liste[i])=="int" and liste[i]>10):
        print "liste[%s]=%s" % (i,liste[i])

#    a while loop
liste=(8,5,0,-2,3,4)
i=0
somme=0
while(i<len(liste) and liste[i]>0):
    print "liste[%s]=%s" % (i,liste[i])
    somme+=liste[i] #   sum=sum+t[i]
    i+=1 #   i=i+1
print "somme=%s" % (somme)
#    end of program

注:

  • 第 1 行:用于声明脚本编码类型的特殊注释,此处为 UTF-8。这取决于所使用的文本编辑器。此处使用 Notepad++:
 
  • 第 4 行:关键字 def 用于定义函数;
  • 第 5-6 行:函数体。它向右缩进一个制表符。这种缩进与 def 语句中的冒号 (:) 共同界定了函数体。这适用于所有带有主体的语句:ifelsewhilefortryexcept
  • 第 12 行:Python 在内部管理变量类型。你可以使用 *type(variable)* 函数确定变量的类型,该函数返回类型为 'type' 的变量。表达式 '%s' % (type(variable)) 是一个字符串,表示该变量的类型;
  • 第 25 行:主程序。它位于脚本中所有函数定义之后。其内容不缩进;
  • 第 28 行:在 Python 中,无需声明变量。Python 区分大小写。变量 Nom 与变量 nom* 是不同的。字符串可以用双引号 " 或单引号 ' 括起来。因此,你可以写 'dupont' 或 "dupont*";
  • 第 31 行:表达式 "xxxx%syyyy%szzzz" % (100, 200) 生成字符串 "xxxx100yyy200szzzz",其中每个 %s 已被元组中的元素替换。%s 是字符串格式化指定符。还有其他格式;
  • 第 34 行:元组 (1,2,3)(注意圆括号)与列表 [1,2,3](注意方括号)之间存在区别。元组是不可变的,而列表是可变的。在两种情况下,第 i 个元素都用 [i] 表示;
  • 第 40 行:range(n) 表示元组 (0,1,2,...,n-1);
  • 第 74 行:len(var) 表示集合 var(元组、列表、字典等)中的元素个数;
  • 第 86 行:其他布尔运算符包括 ornot

屏幕输出如下:

nom=dupont
liste[0]=un
liste[1]=deux
liste[2]=3
liste[3]=4
[chaine1,chaine2,chaine1chaine2]
chaine=chaine1
type[4]=<type 'int'>
type[chaine1]=<type 'str'>
type[['un', 'deux', 3, 4]]=<type 'list'>
type[a change]=<type 'str'>
res1=14
(res1,res2,res3)=[un,0,100]
liste[0]=un
liste[1]=0
liste[2]=100
liste[0]=8
liste[1]=5
somme=13

3.2. 类型转换

这里我们重点介绍涉及 str(字符串)、int(整数)、float(浮点数)和 bool(布尔值)类型的数据的类型转换。


程序 (bases_01b)

#   -*- coding=utf-8 -*-

#   type changes
#   int --> str, float, bool
x=4
print x, type(x)
x=str(4)
print x, type(x)
x=float(4)
print x, type(x)
x=bool(4)
print x, type(x)

#   bool --> int, float, str
x=True
print x, type(x)
x=int(True)
print x, type(x)
x=float(True)
print x, type(x)
x=str(True)
print x, type(x)

#   str --> int, float, bool
x="4"
print x, type(x)
x=int("4")
print x, type(x)
x=float("4")
print x, type(x)
x=bool("4")
print x, type(x)

#   float --> str, int, bool
x=4.32
print x, type(x)
x=str(4.32)
print x, type(x)
x=int(4.32)
print x, type(x)
x=bool(4.32)
print x, type(x)

#  type change error handling
try:
    x=int("abc")
    print x, type(x)
except ValueError, erreur:
    print erreur

#   various Boolean cases
x=bool("abc")
print x, type(x)
x=bool("")
print x, type(x)
x=bool(0)
print x, type(x)
x=None
print x, type(x)
x=bool(None)
print x, type(x)

许多类型转换都是可行的。有些可能会失败,例如第 45–49 行中试图将字符串 'abc' 转换为整数的操作。我们使用 try/except 代码块来处理该错误。该代码块的一般形式如下:


try:
    actions
except Exception, Message:
    actions
finally:
    actions

如果 try 代码块中的任何操作抛出异常(即发生错误),控制流将立即转移到 **except 子句。如果 try 代码块中的操作未抛出异常,则忽略 except 子句。 except 语句的 ExceptionMessage 属性是可选的。当存在时,Exception 指定了 except 语句捕获的异常类型,而 Message 包含与该异常相关的错误消息。如果你想在同一个 try 块内处理不同类型的异常,可以使用多个 except 语句。

finally 语句是可选的。如果存在,无论是否发生异常,finally 代码块中的操作都会执行

我们稍后将再次讨论异常。

第 52 至 61 行展示了将 strintfloatNoneType 类型的数据转换为 boolean 类型的各种尝试。这种转换总是可行的。规则如下:

  • bool(int i) 在 i 为 0 时返回 False,在其他所有情况下返回 True
  • 若 f 为 0.0,则 bool(float f)False,其他情况下均为 True
  • 若字符串长度为 0,则 bool(str string)False,其他情况下均为 True
  • bool(None) 为 False。None 是一个特殊值,表示变量存在但没有值。

屏幕输出如下:

4 <type 'int'>
4 <type 'str'>
4.0 <type 'float'>
True <type 'bool'>
True <type 'bool'>
1 <type 'int'>
1.0 <type 'float'>
True <type 'str'>
4 <type 'str'>
4 <type 'int'>
4.0 <type 'float'>
True <type 'bool'>
4.32 <type 'float'>
4.32 <type 'str'>
4 <type 'int'>
True <type 'bool'>
invalid literal for int() with base 10: 'abc'
True <type 'bool'>
False <type 'bool'>
False <type 'bool'>
None <type 'NoneType'>
False <type 'bool'>
False <type 'bool'>

3.3. 变量的作用域


程序 (bases_02)

#    -*- coding=utf-8 -*-

#    variable scope
def f1():
    #  we use the global variable i
    global i
    i+=1
    j=10
    print "f1[i,j]=[%s,%s]" % (i,j)

def f2():
    #  we use the global variable i
    global i
    i+=1
    j=20
    print "f2[i,j]=[%s,%s]" % (i,j)

def f3():
    #  we use a local variable i
    i=1
    j=30
    print "f3[i,j]=[%s,%s]" % (i,j)

#    tests
i=0
j=0 #  these two variables are known only to a function f
    #  only if it explicitly declares with the global instruction
    #  she wants to use them
f1()
f2()
f3()
print "test[i,j]=[%s,%s]" % (i,j)

结果

1
2
3
4
f1[i,j]=[1,10]
f2[i,j]=[2,20]
f3[i,j]=[1,30]
test[i,j]=[2,0]

注:

  • 该脚本演示了变量 i 的用法,该变量在函数 f1f2 中被声明为全局变量。在此情况下,主程序与函数 f1f2 共享同一个变量 i

3.4. 列表、元组和字典

3.4.1. 一维列表


程序 (bases_03)

#   -*- coding=utf-8 -*-

#   1-dimensional lists
#   initialization
list1=[0,1,2,3,4,5]

#   routes - 1
print "list1 a %s elements" % (len(list1))
for i in range(len(list1)):
    print "list1[%s]=%s" % (i, list1[i])

list1[1]=10;
#   routes - 2
print "list1 a %s elements" % (len(list1))
for element in list1:
    print element

#   addition of two elements
list1[len(list1):]=[10,11]
print ("%s") % (list1)

#   deletion of last two items
list1[len(list1)-2:]=[]
print ("%s") % (list1)

#  addition at the beginning of a tuple list
list1[:0]=[-10, -11, -12]
print ("%s") % (list1)

#   mid-list insertion of two elements
list1[3:3]=[100,101]
print ("%s") % (list1)

#  deletion of two items in the middle of a list
list1[3:4]=[]
print ("%s") % (list1)

注:

  • 数组表示法 array[i:j] 表示数组中从第 i 个元素到第 j-1 个元素;
  • 表示法 [i:] 表示数组中的第 i 个元素及其后的所有元素;
  • 表示法 [:i] 表示列表中从 0i-1 的元素;
  • 第 20 行:print (%s) % (list1) 会显示字符串:"[ list1[0], list1[2], ..., list1[n-1]]"。

结果

list1 a 6 elements
list1[0]=0
list1[1]=1
list1[2]=2
list1[3]=3
list1[4]=4
list1[5]=5
list1 a 6 elements
0
10
2
3
4
5
[0, 10, 2, 3, 4, 5, 10, 11]
[0, 10, 2, 3, 4, 5]
[-10, -11, -12, 0, 10, 2, 3, 4, 5]
[-10, -11, -12, 100, 101, 0, 10, 2, 3, 4, 5]
[-10, -11, -12, 101, 0, 10, 2, 3, 4, 5]

利用某些列表方法,上述代码可以写成另一种形式(bases_03b):

#   -*- coding=utf-8 -*-

#   1-dimensional lists

#   initialization
list1=[0,1,2,3,4,5]

#   routes - 1
print "list1 a %s elements" % (len(list1))
for i in range(len(list1)):
    print "list1[%s]=%s" % (i, list1[i])

list1[1]=10
#   routes - 2
print "list1 a %s elements" % (len(list1))
for element in list1:
    print element

#   addition of two elements
list1.extend([10,11])
print ("%s") % (list1)

#   deletion of last two items
del list1[len(list1)-2:]
print ("%s") % (list1)

#  addition at the beginning of a tuple list
for i in (-12, -11, -10):
    list1.insert(0,i)
print ("%s") % (list1)

#   mid-list insertion
for i in (101,100):
    list1.insert(3,i)
print ("%s") % (list1)

#   mid-list deletion
del list1[3:4]
print ("%s") % (list1)

结果与前一个版本相同。

3.4.2. 字典


该程序(bases_04)

#    -*- coding=utf-8 -*-

def existe(conjoints,mari):
    #  checks whether the husband key exists in the joint dictionary
    if(conjoints.has_key(mari)):
        print "La cle [%s] existe associee a la valeur [%s]" % (mari, conjoints[mari])
    else:
        print "La cle [%s] n'existe pas" % (mari)


#    ----------------------------- Main
#    dictionaries
conjoints={"Pierre":"Gisele", "Paul":"Virginie", "Jacques":"Lucette","Jean":""}

#    routes - 1
print "Nombre d'elements du dictionnaire : %s " % (len(conjoints))
for (cle,valeur) in conjoints.items():
    print "conjoints[%s]=%s" % (cle,valeur)

#    list of dictionary keys
print "liste des cles-------------"
cles=conjoints.keys()
print ("%s") % (cles)

#  list of dictionary values
print "liste des valeurs------------"
valeurs=conjoints.values()
print ("%s") % (valeurs)

#    key search
existe(conjoints,"Jacques")
existe(conjoints,"Lucette")
existe(conjoints,"Jean")

#  deleting a key-value
del (conjoints["Jean"])
print "Nombre d'elements du dictionnaire : %s " % (len(conjoints))
print ("%s") % (conjoints)

注:

  • 第 17 行:couples.items() 返回 couples 字典中 (键, 值) 对的列表
  • 第 22 行:conjoints.keys() 返回 conjoints 字典的键
  • 第 27 行:conjoints.values() 返回 conjoints 字典中的值
  • 第 7 行:spouses.has_key(husband)spouses 字典中存在 husband 键则返回 True,否则返回 False
  • 第 38 行:字典内容可以显示在单行中。

结果

Nombre d'elements du dictionnaire : 4
conjoints[Paul]=Virginie
conjoints[Jean]=
conjoints[Pierre]=Gisele
conjoints[Jacques]=Lucette
liste des cles-------------
['Paul', 'Jean', 'Pierre', 'Jacques']
liste des valeurs------------
['Virginie', '', 'Gisele', 'Lucette']
La cle [Jacques] existe associee a la valeur [Lucette]
La cle [Lucette] n'existe pas
La cle [Jean] existe associee a la valeur []
Nombre d'elements du dictionnaire : 3
{'Paul': 'Virginie', 'Pierre': 'Gisele', 'Jacques': 'Lucette'}

3.4.3. 元组


程序 (bases_05)

#   -*- coding=utf-8 -*-

#   tuples
#   initialization
tab1=(0,1,2,3,4,5)

#   routes - 1
print "tab1 a %s elements" % (len(tab1))
for i in range(len(tab1)):
    print "tab1[%s]=%s" % (i, tab1[i])

#   routes - 2
print "tab1 a %s elements" % (len(tab1))
for element in tab1:
    print element

#   element modification
tab1[0]=-1


结果

tab1 a 6 elements
tab1[0]=0
tab1[1]=1
tab1[2]=2
tab1[3]=3
tab1[4]=4
tab1[5]=5
tab1 a 6 elements
0
1
2
3
4
5
Traceback (most recent call last):
  File "exemple_05.py", line 18, in <module>
    tab1[0]=-1
TypeError: 'tuple' object does not support item assignment

注释:

  • 结果中的第 15–18 行:表明元组无法被修改。

3.4.4. 多维列表


程序 (bases_06)

#   -*- coding=utf-8 -*-

#   multidimensional lists

#   initialization
multi=[[0,1,2], [10,11,12,13], [20,21,22,23,24]]

#   route
for i1 in range(len(multi)):
    for i2 in range(len(multi[i1])):
        print "multi[%s][%s]=%s" % (i1,i2,multi[i1][i2])

#   multidimensional dictionaries
#   initialization
multi={"zero":[0,1], "un":[10,11,12,13], "deux":[20,21,22,23,24]}

#   route
for (cle,valeur) in multi.items():
    for i2 in range(len(multi[cle])):
        print "multi[%s][%s]=%s" % (cle,i2,multi[cle][i2])

结果

multi[0][0]=0
multi[0][1]=1
multi[0][2]=2
multi[1][0]=10
multi[1][1]=11
multi[1][2]=12
multi[1][3]=13
multi[2][0]=20
multi[2][1]=21
multi[2][2]=22
multi[2][3]=23
multi[2][4]=24
multi[zero][0]=0
multi[zero][1]=1
multi[un][0]=10
multi[un][1]=11
multi[un][2]=12
multi[un][3]=13
multi[deux][0]=20
multi[deux][1]=21
multi[deux][2]=22
multi[deux][3]=23
multi[deux][4]=24

3.4.5. 字符串与列表之间的关联


程序 (bases_07)


# -*- coding=Utf-8 -*-
 
# chaîne vers liste
chaine='1:2:3:4'
tab=chaine.split(':')
print type(tab)
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 
# liste vers chaîne
chaine2=":".join(tab)
print "chaine2=%s" % (chaine2)
 
# ajoutons un champ vide
chaine+=":"
print "chaine=%s" % (chaine)
tab=chaine.split(":")
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 
# ajoutons de nouveau un champ vide
chaine+=":"
print "chaine=%s" % (chaine)
tab=chaine.split(":")
 
# affichage liste
print "tab a %s elements" % (len(tab))
print ("%s") % (tab)
 

注:

  • 第 5 行:string.split(separator) 方法将字符串 string分隔符 separator 分割为多个元素,并将其作为列表返回。因此,表达式 '1:2:3:4'.split(":") 返回列表 ('1','2','3','4');
  • 第 13 行:'separator'.join(list) 返回字符串 'list[0]+separator+list[1]+separator+...'。

结果

<type 'list'>
tab a 4 elements
['1', '2', '3', '4']
chaine2=1:2:3:4
chaine=1:2:3:4:
tab a 5 elements
['1', '2', '3', '4', '']
chaine=1:2:3:4::
tab a 6 elements
['1', '2', '3', '4', '', '']

3.5. 正则表达式


程序 (bases_09)

#    -*- coding=utf-8 -*-

import re

# --------------------------------------------------------------------------
def compare(modele,chaine):
    #  compares chain chain with model chain
    #    displaying results
    print "\nResultats(%s,%s)" % (chaine,modele)
    match=re.match(modele,chaine)
    if match:
        print match.groups()
    else:
        print "La chaine [%s] ne correspond pas au modele [%s]" % (chaine,modele)


#  regular expressions in python
#  retrieve the various fields of a string
#  the model: a sequence of numbers surrounded by any characters
#  you only want to retrieve the sequence of digits
modele=r"^.*?(\d+).*?$"

#  the chain is compared with the
compare(modele,"xyz1234abcd")
compare(modele,"12 34")
compare(modele,"abcd")

#  the model: a sequence of numbers surrounded by any characters
#  we want the sequence of digits and the fields that follow and precede them
modele=r"^(.*?)(\d+)(.*?)$"

#  the chain is compared with the
compare(modele,"xyz1234abcd")
compare(modele,"12 34")
compare(modele,"abcd")

#  the template - a date in dd/mm/yy format
modele=r"^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$"
compare(modele,"10/05/97")
compare(modele," 04/04/01 ")
compare(modele,"5/1/01")

#  the model - a decimal number
modele=r"^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$"
compare(modele,"187.8")
compare(modele,"-0.6")
compare(modele,"4")
compare(modele,".6")
compare(modele,"4.")
compare(modele," + 4")
#    end

注:

  • 请注意第 3 行导入的模块。它包含用于处理正则表达式的函数;
  • 第 10 行:将字符串与正则表达式(模式)进行比较,如果字符串与模式匹配则返回 True,否则返回 False
  • 第 12 行:match.groups() 是一个元组,其元素是字符串中与正则表达式中括号内的元素匹配的部分。在以下模式中:
  • ^.*?(\d+).*?,match.groups() 将是一个单元素元组;
  • ^(.*?)(\d+)(.*?)$,此时 match.groups() 将是一个包含 3 个元素的元组。

结果

Resultats(xyz1234abcd,^.*?(\d+).*?$)
('1234',)

Resultats(12 34,^.*?(\d+).*?$)
('12',)

Resultats(abcd,^.*?(\d+).*?$)
La chaine [abcd] ne correspond pas au modele [^.*?(\d+).*?$]

Resultats(xyz1234abcd,^(.*?)(\d+)(.*?)$)
('xyz', '1234', 'abcd')

Resultats(12 34,^(.*?)(\d+)(.*?)$)
('', '12', ' 34')

Resultats(abcd,^(.*?)(\d+)(.*?)$)
La chaine [abcd] ne correspond pas au modele [^(.*?)(\d+)(.*?)$]

Resultats(10/05/97,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
('10', '05', '97')

Resultats( 04/04/01 ,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
('04', '04', '01')

Resultats(5/1/01,^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$)
La chaine [5/1/01] ne correspond pas au modele [^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$]

Resultats(187.8,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '187.8')

Resultats(-0.6,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('-', '0.6')

Resultats(4,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '4')

Resultats(.6,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '.6')

Resultats(4.,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('', '4.')

Resultats( + 4,^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*$)
('+', '4')

3.6. 函数参数传递模式


程序 (bases_10)

#    -*- coding=utf-8 -*-

def f1(a):
    a=2

def f2(a,b):
    a=2
    b=3
    return (a,b)

#    ------------------------ hand
x=1
f1(x)
print "x=%s" % (x)
(x,y)=(-1,-1)
(x,y)=f2(x,y)
print "x=%s, y=%s" % (x,y)

结果

x=1
x=2, y=3

注:

  • 在 Python 中,一切都是对象。有些对象被称为“不可变”:它们无法被修改。数字、字符串和元组就属于这种情况。当 Python 对象作为参数传递给函数时,传递的是对象的引用,除非这些对象是“不可变”的,在这种情况下,传递的是对象的值;
  • 函数 f1(第 3 行)和 f2(第 6 行)旨在演示输出参数的传递。我们希望函数的实际参数能被该函数修改;
  • 第 3–4 行:函数 f1 修改了其形式参数 a。我们需要确认实际参数是否也会被修改。
  • 第 12–13 行:实际参数为 x = 1。第 1 行的结果表明实际参数未被修改。因此,实际参数 x 和形式参数 a两个不同的对象;
  • 第 6–9 行:函数 f2 修改了其形式参数 ab,并将它们作为结果返回;
  • 第 15–16 行:将实际参数 (x, y) 传递给 f2,并将 f2 的结果赋值给 (x, y)。结果的第 2 行显示,实际参数 (x, y) 已被修改。

我们得出结论:当“不可变”对象作为输出参数时,它们必须是函数返回结果的一部分。

3.7. 文本文件


程序 (bases_11)

#    -*- coding=utf-8 -*-

import sys

#    sequential operation of a text file
#  this is a set of lines of the form login:pwd:uid:gid:infos:dir:shell
#  each line is put into a dictionary in the form login => [uid,gid,infos,dir,shell]

# --------------------------------------------------------------------------
def afficheInfos(dico,cle):
    #  displays the value associated with key in the dico dictionary if it exists
    valeur=None
    if dico.has_key(cle):
        valeur=dico[cle]
    if 'list' in str(type(valeur)):
        print "[{0},{1}]".format(cle,":".join(valeur))
    else:
        #  key is not a dictionary key dico
        print "la cle [{0}] n'existe pas".format(cle)           


def cutNewLineChar(ligne):
    #  delete the end-of-line mark if it exists
    l=len(ligne);
    while(ligne[l-1]=="\n" or ligne[l-1]=="\r"):
        l-=1
    return(ligne[0:l]);

#  set the file name
INFOS="infos.txt"

#  we open it in creation
try:
    fic=open(INFOS,"w")
except:
    print "Erreur d'ouverture du fichier INFOS en écriture\n"
    sys.exit()

#    generate arbitrary content
for i in range(1,101):
    ligne="login%s:pwd%s:uid%s:gid%s:infos%s:dir%s:shell%s" % (i,i,i,i,i,i,i)
    fic.write(ligne+"\n")

#  close the file
fic.close()

#  open it for reading
try:
    fic=open(INFOS,"r")
except:
    print "Erreur d'ouverture du fichier INFOS en écriture\n"
    sys.exit()

#    empty dictionary at start
dico={}

#  line reading  
ligne=fic.readline()  
while(ligne!=''):
    #  remove the end-of-line character
    ligne=cutNewLineChar(ligne)

    #  put the line in a table
    infos=ligne.split(":")

    #    retrieve login
    login=infos[0]

    #  remove the first two elements [login,pwd]
    infos[0:2]=[]

    #    create a dictionary entry
    dico[login]=infos

    #  line reading  
    ligne=fic.readline()  

#  close the file
fic.close()

#  using the dictionary
afficheInfos(dico,"login10")
afficheInfos(dico,"X")

注:

  • 第37行:用于在代码中途终止脚本。

结果

infos.txt 文件:

login0:pwd0:uid0:gid0:infos0:dir0:shell0
login1:pwd1:uid1:gid1:infos1:dir1:shell1
login2:pwd2:uid2:gid2:infos2:dir2:shell2
...
login98:pwd98:uid98:gid98:infos98:dir98:shell98
login99:pwd99:uid99:gid99:infos99:dir99:shell99

屏幕输出:

[login10,uid10:gid10:infos10:dir10:shell10]
la cle [X] n'existe pas