【发布时间】:2013-02-20 09:09:11
【问题描述】:
本周开始学习python,所以我想我会用它而不是excel来解析文件路径中的一些字段。
我有大约 3000 个文件都符合命名约定。 /Household/LastName.FirstName.Account.Doctype.Date.extension
例如,这些文件之一可能被命名为:Cosby.Bill..Profile.2006.doc 完整路径是 /Volumes/HD/Organized Files/Cosby, Bill/Cosby.Bill..Profile.2006.doc
在这种情况下:
科斯比,比尔将成为家庭
家庭(Cosby,Bill)是实际文件的封闭文件夹
Bill 是名字
Cosby 将是姓氏
帐户字段被省略
Profile 是文档类型
2006 是日期
doc是扩展名
所有这些文件都位于此目录 /Volumes/HD/Organized Files/ 我使用终端和 ls 将所有文件的列表放入桌面上的 .txt 文件中,我正在尝试解析来自将文件路径分类为上面示例中的类别。理想情况下,我想输出到 csv,每个类别都有一列。这是我丑陋的代码:
def main():
file = open('~/Desktop/client_docs.csv', "rb")
output = open('~/Desktop/client_docs_parsed.txt', "wb")
for line in file:
i = line.find(find_nth(line, '/', 2))
beghouse = line[i + len(find_nth(line, '/', 2)):]
endhouse = beghouse.find('/')
household = beghouse[:endhouse]
lastn = (line[line.find(household):])[(line[line.find(household):]).find('/') + 1:(line[line.find(household):]).find('.')]
firstn = line[line.find('.') + 1: line.find('.', line.find('.') + 1)]
acct = line[line.find('{}.{}.'.format(lastn,firstn)) + len('{}.{}.'.format(lastn,firstn)):line.find('.',line.find('{}.{}.'.format(lastn,firstn)) + len('{}.{}.'.format(lastn,firstn)))]
doctype_beg = line[line.find('{}.{}.{}.'.format(lastn, firstn, acct)) + len('{}.{}.{}.'.format(lastn, firstn, acct)):]
doctype = doctype_beg[:doctype_beg.find('.')]
date_beg = line[line.find('{}/{}.{}.{}.{}.'.format(household,lastn,firstn,acct,doctype)) + len('{}/{}.{}.{}.{}.'.format(household,lastn,firstn,acct,doctype)):]
date = date_beg[:date_beg.find('.')]
print '"',household, '"','"',lastn, '"','"',firstn, '"','"',acct, '"','"',doctype, '"','"',date,'"'
def find_nth(body, s_term, n):
start = body[::-1].find(s_term)
while start >= 0 and n > 1:
start = body[::-1].find(s_term, start+len(s_term))
n -= 1
return ((body[::-1])[start:])[::-1]
if __name__ == "__main__": main()
它似乎工作正常,但是当有另一个封闭文件夹时我遇到了问题,然后它会移动我的所有字段......例如,而不是文件驻留在
/Volumes/HD/Organized Files/Cosby, Bill/
位于 /Volumes/HD/Organized Files/Resigned/Cosby, Bill/
我知道必须有一种不那么笨重的方法来解决这个问题。
【问题讨论】:
-
你好。我在这里闻到了 XY 问题的味道 (meta.stackexchange.com/questions/66377/what-is-the-xy-problem) 你的目标是什么?获得正确的工具来实现您的目标是您真正的 (X) 问题。问这个问题是你试图达到你认为的解决方案的方式(Y)
-
您可以使用os.path.basename() 获取路径的基本名称。然后使用str.split() 以句点分隔名称。
-
布兰登,我昨天晚上发布了一个编辑。我刚刚还发布了第二个编辑。你那边有什么消息吗?
-
刚刚评论了我的发现