/* while 是在有条件控制的情况下 进行的循环 */[root@localhost test1]# vim 13.py//ADD#!/usr/bin/pythonn = 0while True: if n == 10: break print n, 'hello' n += 1[root@localhost test1]# python 13.py0 hello1 hello2 hello3 hello4 hello5 hello6 hello7 hello8 hello9 hello
[root@localhost test1]# vim 14.py//ADD#!/usr/bin/pythonwhile True: print 'hello' input = raw_input("Please input something.q for quit: ") if input == "q": break[root@localhost test1]# python 14.pyhelloPlease input something.q for quit: ehelloPlease input something.q for quit: rhelloPlease input something.q for quit: thelloPlease input something.q for quit: fhelloPlease input something.q for quit: q
[root@localhost test1]# vim 15.py//add#!/usr/bin/pythonx = ''while x != 'q': print 'hello' x = raw_input("Please input something, q for quit: ")/* 首先,要给x定义一个初始值, 然后再继续执行。 这里没有定义输入q后会有什么结果, 但是执行后,输入q则自动退出*/[root@localhost test1]# python 15.pyhelloPlease input something, q for quit: shelloPlease input something, q for quit: shelloPlease input something, q for quit: dhelloPlease input something, q for quit: fhelloPlease input something, q for quit: ghelloPlease input something, q for quit: q
/* 先创建一个文件 */[root@localhost tmp]# cat 1.txt1111//先用一个变量定义,这个变量对应什么文件In [1]: ll = open('/tmp/1.txt')In [2]: llOut[2]://将这个文件或变量打开,并赋予w权限In [4]: ll = open('/tmp/1.txt', 'w')//写变量。括号里为写的内容,此处写的内容会覆盖原来的内容In [5]: ll.write("aa")[root@localhost tmp]# cat 1.txtaa[root@localhost tmp]#/* 有时,需要需要将变量关掉才可以执行看到改变 *//* 再一次打开python的界面需要重新定义变量。*/In [2]: ll = open('/tmp/1.txt')In [3]: ll.read() //从最开始读Out[3]: 'aa'In [4]: ll.read() //当第二次读取时,指针已经读完了前面的内容,就只剩空了Out[4]: ''
/* 读取的具体内容 *///1. 输入需要读取的 前几个字符[root@localhost tmp]# cat 1.txtabcsjdh[root@localhost tmp]#In [1]: ll = open('/tmp/1.txt' , 'r')In [2]: llOut[2]:In [3]: ll.read(2)Out[3]: 'ab'// 2.读取一行In [1]: ll = open('/tmp/1.txt')In [2]: ll.readline()Out[2]: 'abc\n'// 3.读取多行(有多少行读多少行),并且返回一个list// 4. next() 可对一个文件一行一行的读取In [5]: ll = open('/tmp/1.txt')In [6]: ll.readlines()Out[6]: ['abc\n', 'sjdh']In [1]: ll = open('/tmp/1.txt')In [2]: ll.next()Out[2]: 'abc\n'In [3]: ll.next()Out[3]: 'sjdh'In [4]: ll.next()---------------------------------------------------------------------------StopIteration Traceback (most recent call last) in ()----> 1 ll.next()StopIteration:
/* python脚本,对文件进行遍历 */[root@localhost test1]# vim 16.py//ADD#!/usr/bin/pythonll = open('/tmp/1.txt')for line in ll.readlines(): print line,[root@localhost test1]# python 16.pyabcsjdh