BASE_DIR使用print输出正确,但在变量中它只输出C:

2024-06-28 20:46:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在base_dir = settings.BASE_DIR上使用print,它会正确输出所有内容。但是,当我使用这个变量用os.path.join创建一个新变量时,它只输出C:

打印示例: C:\Users\me\Google Drive\gitlab\rootfolder

示例代码,它只输出C:,之后的路径显示正确

blendfile = os.path.join(base_dir, '/var/media', userpathname, newest).replace("\\", "/")

结果如下: C:/var/media/userpathname/newest


Tags: path示例内容basesettingsosvardir
1条回答
网友
1楼 · 发布于 2024-06-28 20:46:24

join函数中的'/var/media'更改为var/media',即从第二个参数中删除前面的斜杠。 因此代码应该是

blendfile = os.path.join(base_dir, 'var/media', userpathname, newest).replace("\\", "/")



示例

In [16]: import os                                                                                                                                    

In [17]: BASE = "Users\me\Google Drive\gitlab\rootfolder"                                                                                             

In [18]: append_path__1 = "/var/media" # with preceeding slash                                                                                                                

In [19]: append_path__2 = "var/media"  # without preceeding slash                                                                                                               

In [20]: os.path.join(BASE,append_path__1)                                                                                                            
Out[20]: '/var/media'

In [21]: os.path.join(BASE,append_path__2)                                                                                                            
Out[21]: 'Users\\me\\Google Drive\\gitlab\rootfolder/var/media'

相关问题 更多 >