你应该使用
import requests
import os
url = 'http://someplace'
folder = 'path/to/folder/'
for card in os.listdir(folder):
data = {'identifier': '.'.join(card.split('.')[:-1]), 'type': 'Inventory Card'}
files = {'card': open(os.path.join(folder, card), 'rb')}
requests.post(url, data=data, files=files, auth=('username', 'pass'))
'.'.join(card.split('.')[:-1])
获取文件名 (in card
),将其拆分为由文件名中的句点分隔的组件,拒绝列表的最后一个元素[:-1]
并重新加入文件名减去扩展名。
使用此语法将处理具有多个句点的文件名,例如foo.20120613.txt
编辑:
列出我目录中文件的示例~/tmp
...
[mpenning@Bucksnort tmp]$ ls
howto regex_trial.xml soln.py
[mpenning@Bucksnort tmp]$
[mpenning@Bucksnort tmp]$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for card in os.listdir('./'):
... print "card:", card
... print " base_name:", '.'.join(card.split('.')[:-1])
...
card: howto
base_name:
card: regex_trial.xml
base_name: regex_trial
card: soln.py
base_name: soln
>>>
请注意,这howto
是一个目录...如果此路径中有目录,您需要在脚本中添加逻辑以跳过目录。