从文件中读取,附加到列表

时间:2016-04-04 03:12:10

标签: python python-3.x

我想:

  1. 从文件中读取
  2. 将每个字符串附加到列表中(从文件,分隔符',')
  3. 遍历列表并将某些元素附加到另外两个列表
  4. end_server_alias = []
    end_server_ip = []
    types = []
    if sys.argv[1] == '-e':
        with(open(sys.argv[2], "r")) as f:
            types.append(line.rstrip().split(",") for line in f)
            k = 0
            while k < len(types):
                print(types[k])
                if types[2*k] is not None:
                    print(1)
                    end_server_ip.append(types[2*k])
                if types[2*k+1] is not None:
                    print(2)
                    end_server_alias.append(types[2*k+1])
                k += 1
        f.close()
    

    我正在阅读的.txt文件是这样的:

    168.1.2.6,www.random1.com 
    
    133.1.3.4,www.random2.com
    

    索引超出范围是我得到的,但我也不确定类型中包含的内容是否为字符串类型。

1 个答案:

答案 0 :(得分:0)

您的解析器存在一些问题,我不太确定您要实现的目标(在测试文件内容方面)。在任何情况下,您都可以使用以下代码转换将文件读入列表:

types,end_server_ip,end_server_alias = [],[],[]
with(open('in.txt', "r")) as f:
    types = [line.rstrip().split(",") for line in f] # Put List syntax to do list compreehension
    k = 0
    while k < len(types):
        print(types[k])
        if types[k][0] is not None: # acess types as index for row, and index for column
            if type(types[k][0]) == type('string'):
                print('Its a String!!!')
            print(1)
            end_server_ip.append(types[k][0])
        if types[k][1] is not None:
            print(2)
            if type(types[k][1]) == type('string'):
                print('Its a String!!!')
            end_server_alias.append(types[k][1])
        k += 1
f.close()

,请注意我更改了您定义types的方式,访问types elements的方式,并添加了一个问题,以查看是否element is a string

请注意,列表具有与行和列等效的内容,因此您需要索引行和列以访问元素。从我的代码中看到的,同样询问元素是否为None对我来说有点奇怪。使用指令创建类型将始终创建字符串。如果您需要数字,您需要自己转换它们。请参阅intfloat等说明。