“用于文件中的行”返回字母,而不是行(python)

时间:2018-09-21 11:29:14

标签: python for-loop

有时,当我使用for循环遍历文件的各行时,我分别得到每个字母而不是每一行。有人可以解释为什么吗?

1 个答案:

答案 0 :(得分:0)

请参见iter()Iterator Types

for a in something:
    pass 

如果something的类型是可迭代的,则a将依次获取您的iterable的所有值。 a的确切含义隐藏在要迭代的对象的__iter__(self):实现内部(afaik)。

  • 如果您在list上进行迭代,它将依次显示所有值。
  • 如果您遍历dict,它将依次向您展示所有dict.keys()
  • 如果您遍历string,它将依次显示每个字符。

生成器和序列也提供迭代,请参见Understanding generators in PythonSequence Types

如果您遍历文件,则将逐行获取(文本文件,而不是二进制文件),除非您首先在文件上调用其他方法():

演示数据:

with open("f.txt","w") as f:
    f.write("""Some Text
Some text after a newline.
More text in a new line.""")

使用可迭代的文件进行迭代:

with open("f.txt","r") as r:
    for c in r: # returns each single line including \n (thats the way next() of file works
        print (c) # appends another \n due to default end='\n' 
print("-"*30)

输出:

Some Text

Some text after a newline.

More text in a new line.
------------------------------

遍历file.read():

with open("f.txt","r") as r:
    t = r.read() # returns a single string of the whole files content
    for c in t:  # you iterate characterwise over a string!
        print (c)
print("-"*30)

输出:

S
o
m
e

[... snipped ...]

l
i
n
e
.
------------------------------

使用readline()遍历文件:

with open("f.txt","r") as r:
    for c in r.readline(): # returns only the first line as string and iterates over this string
        print (c)          # the other lines are omitted!
print("-"*30)

输出:

S
o
m
e

T
e
x
t

------------------------------

使用readlines()遍历文件:

with open("f.txt","r") as r:
    for c in r.readlines(): # returns a list of strings
        print (c)  # appends another \n due to default end='\n' 
print("-"*30)

输出:

Some Text

Some text after a newline.

More text in a new line.
------------------------------

遍历二进制文件:

with open("f.bin","wb") as f:
    f.write(b"294827523")
    f.write(b"2927523")
    f.write(b"-27523")
    f.write(b"\n-27523")

with open("f.bin","rb") as r:
    for b in r:
        print (b)

输出:

b'2948275232927523-27523\n'
b'-27523'