您的位置:首页 > 编程语言 > Python开发

第16课 Python循环体for遍历文件和元组

2017-01-12 15:22 543 查看
1. Python循环遍历元组(tuples)

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

tup=(1,2,3,4,5)

for t in tup:

   print t

else:

  print 'out top'

============= RESTART: =============

1

2

3

4

5

out top

Python循环遍历文件

语法格式:

for val in files

例如for n in open(‘a.txt’,’r’).readlines()

其中a.txt代表的是xx文件,而r代表的是读取方式

>>> help(file.read)

Help on method_descriptor:

read(...)

    read([size]) -> read at most size bytes, returned as a string.

    

    If the size argument is negative or omitted, read until EOF is reached.

    Notice that when in non-blocking mode, less data than what was requested

may be returned, even if no size parameter was given.

>>> help(file.readlines)

Help on method_descriptor:

readlines(...)

    readlines([size]) -> list of strings, each a line from the file.

    Call readline() repeatedly and return a list of the lines so read.

    The optional size argument, if given, is an approximate bound on the

total number of bytes in the lines returned.

>>> help(file.readline)

Help on method_descriptor:

readline(...)

    readline([size]) -> next line from the file, as a string.

    

    Retain newline.  A non-negative size argument limits the maximum

    number of bytes to return (an incomplete line may be returned then).

Return an empty string at EOF.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: