【问题标题】:Problem using formatted string with pandas.to_csv使用带有 pandas.to_csv 的格式化字符串的问题
【发布时间】:2021-05-17 23:18:26
【问题描述】:

我可以使用格式化字符串作为路径来创建目录。 这有效:

directory = r'\{ticker}\options\{exp_date}\{cp}'.format(ticker=ticker, exp_date=exp_date, cp=cp)
check_path_exists(directory)

def check_path_exists(directory):
if not os.path.exists(r'C:\ticker_data'+directory):
    os.makedirs(r'C:\ticker_data'+directory)

但是当我尝试将我的数据框导出到 csv 时,它会返回错误

df.to_csv(r'C:\{ticker}\options\{exp_date}\{cp}\{cp}.csv'.format(ticker=ticker, exp_date=exp_date, cp=cp))

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\MIK\\options\\2021-02-19\\calls\\calls.csv'

它添加了双斜线,我不知道为什么。我什至手动创建了 csv 文件以确保整个路径都存在。

【问题讨论】:

  • 希望this answer有帮助
  • 您的check_path_exists 检查C:\ticker_data\... 而您的to_csv 跳过该路径并写入C:\MIK\...?
  • 杜!我一直在寻找为什么要添加两个斜杠,但这就是问题所在!谢谢。

标签: python pandas csv


【解决方案1】:

克里斯在 cmets 中回答了我的问题。谢谢克里斯。 我没有完整的文件路径。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多