【发布时间】:2017-08-31 07:08:54
【问题描述】:
我在 Google 和 StackOverflow 上都查看了很多类似的问题,但似乎没有适合我的令人满意的解决方案。
我的情况是这样的——
我正在按照here 的步骤使用jQuery File Upload。
我要保存文件的位置是动态的,它取决于username 和session_key。
这是写入文件的函数 -
def handle_uploaded_file(file, session_key, username):
folder_path = os.path.dirname(os.path.realpath(__file__)) + '\\Source\\' + username + '\\session_id_' + session_key
if not os.path.exists(folder_path):
os.makedirs(folder_path)
save_path = folder_path + '\\Source Files'
with open(save_path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
我试图上传一个名为“normal.csv”的文件,但我得到了一个名为“Source Files”的文件,目录中没有扩展名。
当我将 open() 函数内的路径更改为
with open(save_path+file.name, 'wb+') as destination
我有一个名为“Source Filesnormal.csv”的文件。
然后我尝试将save_path 更改为folder_path + '\\Source Files\\',并将save_path+file.name 传递给open(),但随后显示No such file or directory。
我很困惑如何进入该文件夹位置并写入文件。
我不能在这里使用MEDIA_URL,因为它依赖于username 和session_key。
【问题讨论】:
-
使用
os.path.join获取您的目标路径。字符串连接不是实现此目的的好方法。