如何逐行,逐字符读取整个文件?

时间:2018-11-27 08:58:14

标签: python file loops

我正在尝试从文本文件中读取由一个空格分隔的一位数字整数。下面的代码从文件中逐字符读取1行。我想逐行遍历整个文件,一个字符一个字符。该代码如何修改才能做到这一点?

string = ''
with open('map.txt', 'r') as f:
    for line in f:
        string = f.readline()
        row = string.split()
        for character in row:
            if character == '0':
                print('zero')
            elif character == '1':
                print('one')

1 个答案:

答案 0 :(得分:1)

您不需要使用string = f.readline(),因为您已经使用for line in f:并且line变量已经包含文件中的行。另一个错误是row = string.split()。通过这样做,您得到了由空格'abc bbb ccc' -> ['abc', 'bbb', 'ccc']而不是char分割的字符串数组。尝试这样做:

with open('map.txt') as f:
    for line in f:
        # in every step of for-loop line contains new line from your file
        for char in line:
           # now we start iterating over our line and char now contains chars line(including whitespaces)
           if char == '0':
               print('zero')
           if char == '1':
               print('one')