2饿1二 发表于 2015-12-29 09:33:23

python中for语句使用


1
2
3
4
5
root@ubuntu:~/dongbo/tools/python/day2# vi diedai.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
for i in "test.txt":
      print i,




1
2
3
root@ubuntu:~/dongbo/tools/python/day2# python diedai.py
t e s t . t x t
root@ubuntu:~/dongbo/tools/python/day2#






1
2
3
4
5
6
7
8
9
10
11
可以发现是将test.txt打印出来,没有去查找test.txt文件。
下面是将文件内容打印出来了。
root@ubuntu:~/dongbo/tools/python/day2# cat diedai.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_

f =file("/root/dongbo/tools/python/day2/test.txt")
for i in f:
    print i,

root@ubuntu:~/dongbo/tools/python/day2#





1
2
3
root@ubuntu:~/dongbo/tools/python/day2# python diedai.py
wo ai ni chenxiaoyandongbo
dongbo ai chenxiaoyan





下面的方式就是把每个字符打印出来了。

1
2
3
4
5
6
7
8
9
root@ubuntu:~/dongbo/tools/python/day2# cat diedai.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
f =file("/root/dongbo/tools/python/day2/test.txt")
for i in f.readline():
print i,
root@ubuntu:~/dongbo/tools/python/day2# python diedai.py
w o   a i   n i   c h e n x i a o y a n d o n g b o
root@ubuntu:~/dongbo/tools/python/day2#



页: [1]
查看完整版本: python中for语句使用