Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python 2.7中使用变量创建路径名_Python_Variables_Path - Fatal编程技术网

在Python 2.7中使用变量创建路径名

在Python 2.7中使用变量创建路径名,python,variables,path,Python,Variables,Path,我想创建一些文件夹,用命名系统以逻辑方式存储一些模拟的结果 我的代码有4个我正在研究的主要参数,我希望在路径名中使用这些参数动态创建路径,示例如下: a = 'test' b = 2 c = 3 d = 4 os.chdir('./results/test_b_c_d/outputs') 现在我将手动更改a-d的值,因为这些只是一些测试结果。A需要是字符串,但b-d只是整数 我知道我能行 os.path.join('./results/', test, '/outputs/')) “joi

我想创建一些文件夹,用命名系统以逻辑方式存储一些模拟的结果

我的代码有4个我正在研究的主要参数,我希望在路径名中使用这些参数动态创建路径,示例如下:

a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')
现在我将手动更改a-d的值,因为这些只是一些测试结果。A需要是字符串,但b-d只是整数

我知道我能行

os.path.join('./results/', test, '/outputs/'))
“join”命令将在该路径目录中添加该名称的文件夹,但我是否可以使用此命令或类似命令通过更改变量更改实际文件夹名称

谢谢

您正在寻找:

您正在寻找:


要创建包含变量值的字符串(也就是变量值的字符串表示形式),需要
str.format()

然后使用
os.path.join()
以可移植的方式创建完整路径(这样您的代码就可以在任何受支持的操作系统上工作)。另外,最好使用绝对路径(这使代码更可预测),而不是依赖于操作系统特定的东西(“./xxx”)和/或
os.chdir()
。在这里,我使用
o.getcwd()
将当前工作目录用作根目录,但最好使用更可靠的目录,基于当前用户的homedir、应用程序的目录或某些命令行arg或环境变量:

root = os.getcwd() # or whatever root folder you want 
dirpath = os.path.join(root, "results", dirname, "outputs")
最后,使用
os.makedirs
在一次调用中创建整个目录树:

if not os.path.exists(dirpath):
    os.makedirs(dirpath)
注意:

我已经看到我可以做
os.path.join(“./results/”,test,“/outputs/”)


os.path.join()(嗯,变量值的字符串表示形式),您需要
str.format()

然后使用
os.path.join()
以可移植的方式创建完整路径(这样您的代码可以在任何受支持的操作系统上工作)。另外,最好使用绝对路径(这使代码更可预测),而不是依赖于操作系统特定的东西(“./xxx”)和/或
os.chdir()
。这里我使用的是
o.getcwd()
要使用当前工作目录作为根目录,但最好使用更可靠的目录,基于当前用户的homedir、应用程序的目录或某些命令行arg或环境变量:

root = os.getcwd() # or whatever root folder you want 
dirpath = os.path.join(root, "results", dirname, "outputs")
最后,使用
os.makedirs
在一次调用中创建整个目录树:

if not os.path.exists(dirpath):
    os.makedirs(dirpath)
注意:

我已经看到我可以做
os.path.join(“./results/”,test,“/outputs/”)

os.path.join()

您可以混合使用变量值来构建字符串,也可以智能地构建带有正确分隔符的路径(取决于平台)

例如:

a = 'test'
b = 2
c = 3
d = 4

my_path = os.path.join(os.getcwd(), 'results', '{}_{}_{}_{}'.format(a,b,c,d), 'outputs')

os.chdir(my_path)
这不是获取当前工作目录的一种解决方案

您可以混合使用变量值构建字符串和使用正确分隔符智能构建路径(取决于平台)

例如:

a = 'test'
b = 2
c = 3
d = 4

my_path = os.path.join(os.getcwd(), 'results', '{}_{}_{}_{}'.format(a,b,c,d), 'outputs')

os.chdir(my_path)

这不是获取当前工作目录的一种解决方案,因此,如果我理解正确,您希望生成路径
“/results/test\u 2\u 3\u 4/outputs”
?是的,但每次我想保存数据时,我都会更改b、c和d的值,所以我想在“/results/”中有一大堆文件夹,每个文件夹都有一个名为“outputs”的文件夹。因此,如果我理解正确,您希望生成路径
”/results/test\u 2\u 3\u 4/outputs”
?是的,但是每次我想保存数据时,我都会更改b、c和d的值,所以我想在“/results/”中有一大堆文件夹,它们有不同的名称。每一个文件夹中都有一个名为“outputs”的文件夹。这太棒了!谢谢:)这太棒了!谢谢:)