Python中的用for,while迴圈遍歷檔案例項
阿新 • • 發佈:2018-11-27
使用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... [root[@localhost](https://my.oschina.net/u/570656) ~]# cat /tmp/1.txt 1111 [root[@localhost](https://my.oschina.net/u/570656) ~]#
只讀方式開啟:
In [26]: open('/tmp/1.txt')
Out[26]: <open file '/tmp/1.txt', mode 'r' at 0x20860c0>
In [27]: fd = open('/tmp/1.txt')
In [28]: fd
Out[28]: <open file '/tmp/1.txt', mode 'r' at 0x20861e0>
In [29]: type(fd)
Out[29]: file
以寫方式開啟:
In [34]: fd = open('/tmp/1.txt','w') In [35]: fd.write('2222\n') In [36]: fd.close() [root[@localhost](https://my.oschina.net/u/570656) ~]# cat /tmp/1.txt 2222 [root[@localhost](https://my.oschina.net/u/570656) ~]#
以追加方式開啟:
In [34]: fd = open('/tmp/1.txt','a')
In [35]: fd.write('3333\n')
In [36]: fd.close()
[root[@localhost](https://my.oschina.net/u/570656) ~]# cat /tmp/1.txt
2222
3333
[[email protected] ~]#
read():
In [41]: fd.read() Out[41]: '2222\n3333\n' In [42]: fd.read() Out[42]: '' In [49]: fd.readline() Out[49]: '2222\n' In [50]: fd.readline() Out[50]: '3333\n' In [51]: fd.readline() Out[51]: '' In [52]:
read() 和readline()返回的是字串:
readlines()返回的是列表:
in [52]: fd = open('/tmp/1.txt')
In [53]: fd.readlines()
Out[53]: ['2222\n', '3333\n']
指令碼:
#!/usr/bin/python
fd = open('/tmp/1.txt')
for line in fd:
print line,
fd.close()
[[email protected] 20171228]# python read_file.py
2222
3333
[[email protected] 20171228]#
使用while迴圈遍歷檔案
指令碼:
#!/usr/bin/python
fd = open('/tmp/1.txt')
while True:
line = fd.readline()
if not line:
break
print line,
fd.close()
[[email protected] 20171228]# python read_fi_while.py
2222
3333
[[email protected] 20171228]#
with open開啟檔案 :
#!/usr/bin/python
with open('/tmp/1.txt') as fd:
while True:
line = fd.readline()
if not line:
break
print line,