我的代码的目的是读取文本文件,将行添加到数组中,迭代数组中的每个元素,将元素转换为字符串,并返回包含此字符串的csv文件中的行。我的代码是:
#Read cvs File from url
import csv
import urllib2
url = 'mycsvfile.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
#Read txt File
import linecache
fileName = 'myfile.txt'
myFile = open(fileName,'r')
list_of_lists = []
try:
for line in myFile:
list_of_lists.append(line.strip())
#Lookup Lines
for element in list_of_lists:
elementstring=''.join(element)
for row in cr:
if elementstring in row:
print row
finally:
myFile.close()
代码不显示任何内容。
答案 0 :(得分:2)
我的猜测是,在csv阅读器的第一次迭代中,您没有满足条件的任何行 - if elementstring in row:
(对于第一个elementstring
)。在这次迭代之后,你已经耗尽了你的csv并且它已经到了最后,试图再次迭代它不起作用。
尝试在循环外部打开url和csv并将每个内部行转换为一个集合,然后将它们全部添加到列表中,然后使用它循环 -
#Read cvs File from url
import csv
import urllib2
url = 'mycsvfile.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
csvset = [set(i) for i in cr]
#Read txt File
import linecache
fileName = 'myfile.txt'
myFile = open(fileName,'r')
list_of_lists = []
try:
for line in myFile:
list_of_lists.append(line.strip())
#Lookup Lines
for element in list_of_lists:
elementstring=''.join(element)
for row in csvset:
if elementstring in row:
print row
finally:
myFile.close()