ループ反復するファイルに使用
ファイルを開きます
開いた
R:リードモードでオープン に書き込みモードで、W :追加モードを開く 読み書きモードでオープン:R + 書き込みモードでオープン(W参照):+ Wを A +:読み書きモードでオープン(A参照) RBが:でONバイナリ読み出しモード WB:バイナリライトモードでオープン(Wを参照) オープンバイナリ追加モード(Aを参照):AB&が RB +:バイナリ読み書きモードでオープン(R&LT +参照) WB +:バイナリ読み書きモードでオープン(+ W参照) AB +:バイナリ読み書きモードでオープン(+を参照してください)
ビューヘルプ:
オープン(...) オープン(名[、モード[、バッファリング]]) - >ファイルオブジェクトが ファイルを使用してファイルを開き()タイプ、ファイルオブジェクトを返します。これは、 ファイルを開くための好ましい方法。詳細については、ファイル.__ doc__内の例題を参照してください。 (END)...スキップ... [ルート[@localhost](https://my.oschina.net/u/570656)〜]#猫/tmp/1.txt 1111 [ルート[@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 [root@localhost ~]#
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() [root@localhost 20171228]# python read_file.py22223333[root@localhost 20171228]#
使用while循环遍历文件
脚本:
#!/usr/bin/python fd = open('/tmp/1.txt') while True: line = fd.readline() if not line: break print line, fd.close() [root@localhost 20171228]# python read_fi_while.py 22223333 [root@localhost 20171228]#
with open打开文件 :
#!/usr/bin/python with open('/tmp/1.txt') as fd: while True: line = fd.readline() if not line: break print line,