为什么我在这里得到FileNotFoundException?

时间:2014-11-22 20:43:30

标签: python file exception filenotfoundexception

只是尝试从考试网站批量下载一些过去的论文,同时提高我的编程技巧。我已经研究了很多东西,不知道为什么这不起作用。

错误:

Downloading C:\Users\Azmat\Desktop\Practise Exams\Biology\January 2012 Question Paper.pdf
Traceback (most recent call last):
  File "testDownloader.py", line 31, in <module>
    with open(filename, 'w+') as code:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Azmat\\Desktop\\Practise Exams\\Biology\\January 2012 Question Paper.pdf'

我的代码:

import urllib.request, urllib.parse, urllib.error

years = [12, 13]
months = ["JAN", "JUN"]
subjects = ["BL", "CH", "PH"]
files = ["QP", "W-MS", "WRE"]
sub = {
    'BL': 'Biology',
    'CH': 'Chemistry',
    'PH': 'Physics',
}
mon = {
    'JAN' : 'January',
    'JUN' : 'June',
}
fil = {
    'QP' : 'Question Paper',
    'W-MS' : 'Mark scheme',
    'WRE' : "Examiner's report"
}

for year in years:
    for month in months:
        for subject in subjects:
            for file in files:
                url =('http://filestore.aqa.org.uk/subjects/AQA-%s1HP-%s-%s%d.PDF' % (subject, file, month, year))
                filename = 'C:\\Users\\Azmat\\Desktop\\Practise Exams\\' + sub[subject] + '\\' + mon[month] + ' 20%d ' % year + fil[file] + '.pdf' 
                print("Downloading " + filename) 
                f = urllib.request.urlopen(url)
                data = f.read()
                with open(filename, 'w+') as code:
                    code.write(data)

1 个答案:

答案 0 :(得分:0)

在打开要写入的文件之前,您要写入文件的目录必须存在。您可以将os.mkdir用于单个目录,或os.makedirs以递归方式创建目录。

import os
for subject in sub.values():
    os.makedirs('C:\\Users\\Azmat\\Desktop\\Practise Exams\\' + subject)