Python中的用for,while循环遍历文件实例
使用for循环遍历文件打开文件
open
r:以读模式打开
w:以写模式打开
a:以追加模式打开
r+:以读写模式打开
w+:以读写模式打开(参见w)
a+:以读写模式打开(参见a)
rb:以二进制读模式打开
wb:以二进制写模式打开(参见w)
ab:以二进制追加模式打开(参见a)
rb+:以二进制读写模式打开(参见r+)
wb+:以二进制读写模式打开(参见w+)
ab+:以二进制读写模式打开(参见a+)
查看帮助:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object.This is the
preferred way to open a file.See file.__doc__ for further information.
(END)...skipping...
# cat /tmp/1.txt
1111
#
只读方式打开:
In : open('/tmp/1.txt')
Out: <open file '/tmp/1.txt', mode 'r' at 0x20860c0>
In : fd = open('/tmp/1.txt')
In : fd
Out: <open file '/tmp/1.txt', mode 'r' at 0x20861e0>
In : type(fd)
Out: file
以写方式打开:
In : fd = open('/tmp/1.txt','w')
In : fd.write('2222\n')
In : fd.close()
# cat /tmp/1.txt
2222
#
以追加方式打开:
In : fd = open('/tmp/1.txt','a')
In : fd.write('3333\n')
In : fd.close()
# cat /tmp/1.txt
2222
3333
#
read():
In : fd.read()
Out: '2222\n3333\n'
In : fd.read()
Out: ''
In : fd.readline()
Out: '2222\n'
In : fd.readline()
Out: '3333\n'
In : fd.readline()
Out: ''
In :
read()和readline()返回的是字符串:
readlines()返回的是列表:
in : fd = open('/tmp/1.txt')
In : fd.readlines()
Out: ['2222\n', '3333\n']
脚本:
#!/usr/bin/python
fd = open('/tmp/1.txt')
for line in fd:
print line,
fd.close()
# python read_file.py
2222
3333
#
使用while循环遍历文件
脚本:
#!/usr/bin/python
fd = open('/tmp/1.txt')
while True:
line = fd.readline()
if not line:
break
print line,
fd.close()
# python read_fi_while.py
2222
3333
#
with open打开文件 :
#!/usr/bin/python
with open('/tmp/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,
页:
[1]