我试图遍历目录中的csv文件,从csv文件中提取URL,然后将它们保存在列表中。我可以使用以下代码为一个文件成功完成此操作:
sec_urls = []
directory = '/Users/nicolacornforth/index'
for filename in os.listdir(directory):
if filename.endswith('.csv'):
with open(os.path.join(INDEX_DIR, filename), newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for line in reader:
url = line[4].strip()
sec_urls.append(url)
print(url, 'downloaded and added to list')
但是,当我使用一个for循环尝试为所有文件完成此操作时,我收到了一个我没有命名的特定文件的错误消息,并且该错误肯定在列表中(我可以重写上面的代码以将其单档案)。代码和相应的错误如下:
<ipython-input-27-f0b28aed085c> in <module>
4 for filename in os.listdir(directory):
5 if filename.endswith('.csv'):
----> 6 with open(os.path.join(INDEX_DIR, filename), newline='') as csvfile:
7 reader = csv.reader(csvfile, delimiter=',')
8 for line in reader:
FileNotFoundError: [Errno 2] No such file or directory: './index/2007Q2.csv'
res.getwirter
请多多帮助,我是绝对的初学者。