我有一个python脚本从csv文件中提取文件名,并通过向文件中的字段添加值来更新该文件。我的问题是我需要更新的文件实际上是在一个子目录中,文件夹名称与我需要更新的文件完全无关。
我的.csv列表是这样的:
file1, fieldx, value
file2, fieldx, value
和文件在这样的文件夹中:
abcd/file1
efgh/file2
如何更新我的代码以查找文件夹中的文件?我是Python的新手,我知道它涉及glob,glob2或os.walk,但我不确定如何嵌套/循环,因为我从.csv中提取文件名值。
这是我的代码:
import csv
startfile = raw_input("Please enter the name of the csv file: ")
with open(startfile, 'r') as f:
reader = csv.reader(f)
changelist = list(reader)
for x in changelist:
linnum = 0
fname=x[0]+".xml"
fieldlookup = x[1]
with open(fname) as f:
for num, line in enumerate(f, 1):
if fieldlookup in line:
linnum = num
f.close()
f = open(fname, 'r')
lines = f.readlines()
if linnum > 0:
lines[linnum-1] = " <"+fieldlookup+">"+str(x[2])+"</"+fieldlookup+">\n"
f.close()
f = open(fname, 'w')
f.writelines(lines)
f.close()
print "success!"+str(x[0])+"\n"
如果只存在一个级别的子目录,您应该只能通过以下方式执行:
import glob
...
fname=x[0]+".xml"
real_fname=glob.glob("./*/"+fname)
然后使用real_fname。如果您需要跨平台兼容性,您还可以使用os.path.join而不是+。