python2.7csv:通过添加split()遍历行并存储在数组中

2024-09-28 01:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道我在循环中的评论是否正确。变量'device'会像我希望的那样是“列表列表”吗?如果是,我可以用设备[0][0]调用数据吗?或者,假设我想要第三行和第二项,使用设备[2][1]?在

def deviceFile():
    devFile = raw_input('Enter the full file path to your device list file: \n-->')
    open(devFile, 'r')
    device = []
    for line in devFile:
        # creating an array here to hold each line. Call with object[0][0]
        device.append(line.split(','))
    return(device)

编辑:

^{pr2}$

这更像是一个‘我在逻辑上做这件事吗’而不是‘我的代码完美’这类问题。我希望csv的每一行都是它自己的列表,并且可以通过在主程序中调用它来访问它:

设备=设备文件()

机器=设备[0][0]

返回第一行的第一项

机器=设备[2][1]

返回第三行的第二项


Tags: theto数据机器列表inputrawdevice
2条回答

如果我错了,请纠正我,我认为您是在尝试读取一个文件,然后将文件中的每一行(用逗号分隔)存储到一个数组中。例如,如果你有一个文本文件简单地写着“一,二,三”,你想让它创建一个数组['one','two',three']?如果是这样,则不需要for循环,只需执行以下操作:

def deviceFile():
    devFile = raw_input('Enter the full file path to your device list file: \n >')
    myFile = open(devFile, 'r') # Open file in read mode
    readFile = myFile.read() # Read the file

    # Replace enter characters with commas
    readFile = readFile.replace('\n', ',')
    # Split the file by commas, return an array
    return readFile.split(',')

不需要for循环的原因是结构分裂()已返回数组。事实上,你甚至不需要附加“设备”,你根本不需要设备。有关详细信息,请参阅string documentation。在

您的问题是,您没有对file对象(即open返回的对象)执行任何操作,而是试图将文件名当作文件对象来操作。所以,改变一下:

devFile = raw_input('Enter the full file path to your device list file: \n >')
open(devPath, 'r')

为此:

^{pr2}$

一旦你这样做了,它就“起作用了”,但可能不是你想要的那样。例如,对于此文件:

abc, def
ghi, jkl

你会得到这个:

[['abc', ' def\n'], ['ghi', ' jkl\n']]

存在'\n'字符是因为for line in devFile:返回保留了换行符的行。如果你想摆脱它们,你必须做些事情,比如rstrip('\n')。在

空间没有魔法,因为空间不能做任何事情。你让它在','上拆分'abc, def',你将得到'abc'和{}。如果你想去掉它们,strip结果。在

你还有很多其他的小问题,例如,你从来没有关闭过文件,但它们都不会真正阻止你的代码工作。在

所以:

def deviceFile():
    devPath = raw_input('Enter the full file path to your device list file: \n >')
    devFile = open(devPath, 'r')
    device = []
    for line in devFile:
        # creating an array here to hold each line. Call with object[0][0]
        device.append([value.strip() for value in line.rstrip('\n').split(',')])
    return(device)

现在您将返回这个:

[['abc', 'def'], ['ghi', 'jkl']]

这看起来很复杂。在可以split之前,在每一行上调用rstrip这没什么大不了的,但是对每个值调用strip的列表理解会让人有点难以阅读。如果你不知道什么是列表理解(这似乎很有可能,因为你已经为device列表设置了一个append的显式循环),你必须做如下事情:

device = []
for line in devFile:
    values = []
    for value in line.rstrip('\n').split(','):
        values.append(value.strip())
    device.append(values)

然而,有一个更简单的方法来做到这一点。标准库中的^{} module负责处理新行和空白的所有棘手问题,以及您还没有想到的事情(如引用或转义的值)。在

def deviceFile():
    devPath = raw_input('Enter the full file path to your device list file: \n >')
    with open(devPath) as devFile:
        return list(csv.reader(devFile))

相关问题 更多 >

    热门问题