Python更改文件路径名称

时间:2018-02-22 09:40:09

标签: python file

我想用字符串替换我的文件夹路径,我收到错误 我试过这个:

a="ram"
my_list.to_csv(r'E:\'+str(a)+'\4\mani.csv' )

2 个答案:

答案 0 :(得分:1)

你犯了字符串连接错误。尝试str.format以避免此类错误。

import os

a = "ram"
file_path = r'E:\{a}\4\mani.csv'.format(a=a)
directory = os.path.dirname(file_path)
os.makedirs(path, exist_ok=True)
my_list.to_csv(file_path)

答案 1 :(得分:0)

>>> a = "ram"
>>> filename = 'mani.csv'
>>> absolute_path = os.path.join('E:', '4', a, filename)
>>> my_list.to_csv(absolute_path)