日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用python画枫叶-Python中的用for,while循环遍历文件实例

發(fā)布時間:2023/12/20 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用python画枫叶-Python中的用for,while循环遍历文件实例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用for循環(huán)遍歷文件

打開文件

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]:

In [27]: fd = open('/tmp/1.txt')

In [28]: fd

Out[28]:

In [29]: type(fd)

Out[29]: file

以寫方式打開:

In [34]: fd = open('/tmp/1.txt','w')

In [35]: fd.write('2222 ')

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 ')

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 3333 '

In [42]: fd.read()

Out[42]: ''

In [49]: fd.readline()

Out[49]: '2222 '

In [50]: fd.readline()

Out[50]: '3333 '

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 ', '3333 ']

腳本:

#!/usr/bin/python

fd = open('/tmp/1.txt')

for line in fd:

print line,

fd.close()

[root@localhost 20171228]# python read_file.py

2222

3333

[root@localhost 20171228]#

使用while循環(huán)遍歷文件

腳本:

#!/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

2222

3333

[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,

總結(jié)

以上是生活随笔為你收集整理的用python画枫叶-Python中的用for,while循环遍历文件实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。