我的代码的目的是读取文本文件,将行添加到数组中,迭代数组中的每个元素,将元素转换为一个字符串,并从csv文件返回包含此字符串的行。我的代码是:Python嵌套循环以匹配字符串从文本文件到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()
该代码不显示任何内容。
我看不到任何明显问题。为什么不添加'print repr(elementstring)'和'print repr(row)'来查看元素是否真的匹配? –
顺便说一下,你的'list_of_lists'不会包含列表,而只是字符串,所以'''.join'是毫无意义的。另外,为什么要创建'list_of_lists',而不是直接迭代文件? –
我同意@tobias_k,并会添加一件事:您是否使用过Python调试器?调试器可以让你一行一行地查看代码,并查看每个步骤的所有变量。这是理解你的代码真正在做什么的好方法,所以你不必说“它不工作,我不知道为什么。”我写了[这里有几个Python调试器](http://stackoverflow.com/a/16474706/1202830)。 –