Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以从特定的csv行读取?_Python_File Io - Fatal编程技术网

Python 是否可以从特定的csv行读取?

Python 是否可以从特定的csv行读取?,python,file-io,Python,File Io,我刚刚发现不可能写入csv文件中的特定行(仅在末尾) 我刚刚遇到了另一个我很难解决的障碍,那就是读取csv文件中的特定行。 我发现实现这一目标的一个方法是: with open('file.csv',newline = '') as csvfile: spamreader = csv.reader(csvfile,delimiter=',',quotechar = '"') lines = [] for row in spamreader: lines.a

我刚刚发现不可能写入csv文件中的特定行(仅在末尾)

我刚刚遇到了另一个我很难解决的障碍,那就是读取csv文件中的特定行。 我发现实现这一目标的一个方法是:

with open('file.csv',newline = '') as csvfile:
    spamreader = csv.reader(csvfile,delimiter=',',quotechar = '"')
    lines = []
    for row in spamreader:
        lines.append(row)

print('What line do you want to read from?')
line = lines[int(input())-1] #I think the -1 is right. since lists start at 0
然而,我认为这可能是一种效率稍低的方法,因为列表“行”中的行越多,程序使用的RAM就越多

有人能告诉我这是否是一种有效的方法吗?否则,我就这么做了

我有没有办法做这样的事

spamreader.readRow(5) #I just made this up, but is there a similar function?
这是我一直在使用的页面,有可能我跳过了它


另外,我在编程方面不是很在行,所以如果有高级答案,你能试着让解释保持相当简单吗?

如果你想从第123行开始阅读:

for _ in range(122): 
    spamreader.next()
for row in spamreader:
    ...
对于Python3,它似乎是

    next(spamreader)

您还可以通过使用
find
seek
将光标移动到特定字节,在文件中进行导航。这两种方法可能重复,也可以查看。我查看了您的两种解决方案,并在每一页上尝试了每个答案,但都不起作用。虽然这可能会引起长时间的评论,但我不同意我的问题已经在你的链接中得到了回答。(我可能错了!)首先:我尝试使用enumerate方法。我不知道该怎么做。最上面的答案是“如果i==行数:#行数-1”。。。我不知道该怎么办。第二:我尝试以“line=linecache.getline('file.csv',int(input())”的方式使用linecache,但这导致了许多错误。第三:我尝试使用“selection=[行对行,如果行[2]=='a']我不认为这会起作用,因为我想给出一个行号,然后跳到那一行。这不起作用的原因是我不相信有办法从行中提取行号。如果你看OP给出的示例,他正在创建一个列表,列出可能选择的行,如果是特定的“单元格”“包含某些信息。这给了我一个错误:“\u csv.reader”对象没有“next”属性。我没有尝试使用Python 3,请尝试以下操作:
next(spamreader)
()。对于我(Python 2.7,csv 1.0),它可以工作。
dir(spamreader)有什么作用?”
还你吗?该死,我真不敢相信我没听清楚。非常感谢,你已经解决了我的问题:)。我设法让它工作的方法是:
对于范围内的行(int(input()):chosenRow=next(spamreader)
,然后我可以用chosenRow做任何我想做的事情。非常感谢。太好了。然后接受答案:)特别是因为它比上面建议的帖子中的更好。。。