我想知道我在循环中的评论是否正确。变量'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]
返回第三行的第二项
如果我错了,请纠正我,我认为您是在尝试读取一个文件,然后将文件中的每一行(用逗号分隔)存储到一个数组中。例如,如果你有一个文本文件简单地写着“一,二,三”,你想让它创建一个数组['one','two',three']?如果是这样,则不需要for循环,只需执行以下操作:
不需要for循环的原因是结构分裂()已返回数组。事实上,你甚至不需要附加“设备”,你根本不需要设备。有关详细信息,请参阅string documentation。在
您的问题是,您没有对file对象(即
open
返回的对象)执行任何操作,而是试图将文件名当作文件对象来操作。所以,改变一下:为此:
^{pr2}$一旦你这样做了,它就“起作用了”,但可能不是你想要的那样。例如,对于此文件:
你会得到这个:
存在
'\n'
字符是因为for line in devFile:
返回保留了换行符的行。如果你想摆脱它们,你必须做些事情,比如rstrip('\n')
。在空间没有魔法,因为空间不能做任何事情。你让它在}。如果你想去掉它们,
','
上拆分'abc, def'
,你将得到'abc'
和{strip
结果。在你还有很多其他的小问题,例如,你从来没有关闭过文件,但它们都不会真正阻止你的代码工作。在
所以:
现在您将返回这个:
这看起来很复杂。在可以
split
之前,在每一行上调用rstrip
这没什么大不了的,但是对每个值调用strip
的列表理解会让人有点难以阅读。如果你不知道什么是列表理解(这似乎很有可能,因为你已经为device
列表设置了一个append
的显式循环),你必须做如下事情:然而,有一个更简单的方法来做到这一点。标准库中的^{} module 负责处理新行和空白的所有棘手问题,以及您还没有想到的事情(如引用或转义的值)。在
相关问题 更多 >
编程相关推荐