在不同的目录中打开文件

Open file in different directory

我写了一个函数,我想打开子目录 'data' 中的文件。

def _save_exrates(date, rates):
    """
    Saves the exchange rates data for date 'date' in the appropriate exchange 
    rates file, as described below.
    """
    file = open(os.path.join('data', 'rates-'+date+'.csv'), 'wt')
    w = csv.writer(file, lineterminator='\n')
    w.writerow(['Code', 'Rate'])
    for key, value in sorted(rates.items()):
        w.writerow([key, value])
    file.close()

我的程序在 Windows 上工作,但是当我在 Mac 上 运行 时,我收到错误:

FileNotFoundError: [Errno 2] No such file or directory: 'data/rates-2001-03-03.csv'

如何打开 Mac 和 Windows 上的目录?

确保先创建目录,然后再在其中创建文件。