在python中从文件加载文本

时间:2018-11-27 05:03:15

标签: python file

im试图从python文件中逐行加载单位数字,此代码会显示错误消息:

line 27, in <module>
environment.environment1.load_map(environmentVector)
TypeError: load_map() takes 1 positional argument but 2 were given

此处是源代码:(main.py)

environmentVector = []
environment.environment1 = environment.environment(160, 100, 32, 32)
environment.environment1.load_map(environmentVector)

environment.py:

    def load_map(environmentVector):
        string = ''
        with open('map.txt', 'r') as f:
            for line in f:
                string = f.readline()
                row = []
                for character in string:
                    if character == '0':
                        pass
                    elif character == '1':
                        environmentVector.append(environment)

1 个答案:

答案 0 :(得分:1)

首先,如果load_map是类的方法,则它需要采用的第一个参数是self。添加self,或使用load_map@staticmethod标记为静态方法。请参见this

关于load_map函数:split无需遍历字符串。将这样的地图存储到2D列表中也很有意义。试试这个:

def load_map(self, environmentVector):
    with open('map.txt', 'r') as f:
        for line in f:
            nums = list(map(int, line.split()))
            environmentVector.append(nums)