需要一些帮助从列表中删除数据,并再次将其附加在同一个列表中
问题描述:
我开发了一个Django应用程序,用户可以在其中上传多个文件。我可以上传所有多个文件和它的路径中由逗号分隔的列表的形式在MySQL数据库。例如(,)我已上载的三个文件需要一些帮助从列表中删除数据,并再次将其附加在同一个列表中
- 记录一个Defect.docx, 2.Mocks( 1).PPTX和 3.Mocksv2.pptx
和它被存储在数据库中作为以下的(转换单个文件路径成列表,并在下面的形式加入的所有路径的结果):
FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx,
现在我需要d帮助删除特定文件。例如,当我删除Logging a Defect.docx时,我应该删除列表中的第一个元素,并保留其他两个路径。我只会发送文件的名称。
我正在检索作为列表的路径,然后我必须检查被传递的doc的名称是否存在于列表的每个元素中,如果匹配,那么我应该删除该元素以保持其他元素不变。如何解决这个问题?听起来像Python问题比Django问题更多。
答
使用列表表达式过滤分裂的文本,并使用连接功能
>>> db_path = 'FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
>>> file_to_delete = 'Logging a Defect.docx'
>>> file_separator = ","
>>> new_db_path = [
... path.strip()
... for path in db_path.split(file_separator)
... if path.strip() and file_to_delete not in path
... ]
>>> string_to_save = file_separator.join(new_db_path)
>>> string_to_save
'FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
答
可以读取数据库中的文字,然后用列表的remove
方法蟒蛇,然后写回新值DATABSE:
text = "FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx,"
splitted = text.split(',')
#filename is the one you want to delete
entry = "FileStore/client/{filename}".format(filename="Mocks (1).pptx")
if entry in splitted:
splitted.remove(entry)
newtext = ""
for s in splitted:
newtext += s
newtext += ','
写信回newtext数据库
答
不敢吹嘘或任何重建的字符串,但我想到了我自己的逻辑对于m问题。它看起来不那么复杂,但它工作正常。
db_path = 'FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
path_list = db_path.split(",")
doc = 'Logging a Defect.docx'
for i in path_list :
if doc in i:
y.remove("FileStore/"+client+"/"+doc)
new_path = ",".join(y)
print new_path
这就是我一直在寻找的。非常感谢您的帮助。 – 2014-09-24 11:39:48