/* while 是在有条件控制的情况下 进行的循环 */
[root@localhost test1]# vim 13.py
//ADD
#!/usr/bin/python
n = 0
while True:
if n == 10:
break
print n, 'hello'
n += 1
[root@localhost test1]# python 13.py
0 hello
1 hello
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello
[root@localhost test1]# vim 14.py
//ADD
#!/usr/bin/python
while True:
print 'hello'
input = raw_input("Please input something.q for quit: ")
if input == "q":
break
[root@localhost test1]# python 14.py
hello
Please input something.q for quit: e
hello
Please input something.q for quit: r
hello
Please input something.q for quit: t
hello
Please input something.q for quit: f
hello
Please input something.q for quit: q
[root@localhost test1]# vim 15.py
//add
#!/usr/bin/python
x = ''
while x != 'q':
print 'hello'
x = raw_input("Please input something, q for quit: ")
/* 首先,要给x定义一个初始值,
然后再继续执行。 这里没有定义输入q后会有什么结果,
但是执行后,输入q则自动退出
*/
[root@localhost test1]# python 15.py
hello
Please input something, q for quit: s
hello
Please input something, q for quit: s
hello
Please input something, q for quit: d
hello
Please input something, q for quit: f
hello
Please input something, q for quit: g
hello
Please input something, q for quit: q
/* 先创建一个文件 */
[root@localhost tmp]# cat 1.txt
1111
//先用一个变量定义,这个变量对应什么文件
In [1]: ll = open('/tmp/1.txt')
In [2]: ll
Out[2]: <open file '/tmp/1.txt', mode 'r' at 0x99d81d8>
//将这个文件或变量打开,并赋予w权限
In [4]: ll = open('/tmp/1.txt', 'w')
//写变量。括号里为写的内容,此处写的内容会覆盖原来的内容
In [5]: ll.write("aa")
[root@localhost tmp]# cat 1.txt
aa[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.txt
abc
sjdh[root@localhost tmp]#
In [1]: ll = open('/tmp/1.txt' , 'r')
In [2]: ll
Out[2]: <open file '/tmp/1.txt', mode 'r' at 0x9392180>
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)
<ipython-input-4-e9a4e3e4293f> in <module>()
----> 1 ll.next()
StopIteration:
/* python脚本,对文件进行遍历 */
[root@localhost test1]# vim 16.py
//ADD
#!/usr/bin/python
ll = open('/tmp/1.txt')
for line in ll.readlines():
print line,
[root@localhost test1]# python 16.py
abc
sjdh