我有一个csv文件,其中有一个带有倍数值的列。我试图在具有多个子目录的根目录中找到所有文件,其名称以该列的每个值开头,并返回这些文件所在的路径,并将其写在csv上。例如:该列的第一个值是'linux',因此如果我有两个名为'linux01.jpg'和'linuximg.jpg'的文件,该函数将在csv中返回两个路径。那就是我现在所拥有的,而我的csv是空白的。谢谢你。
import csv
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
ifile = open('carte.csv', 'rb')
reader = csv.reader(ifile)
ofile = open('output.csv', 'wb')
writer = csv.writer(ofile, delimiter='\t')
for row in reader:
find_key = find(row[3], '/home/ro/Desktop/search/IDBUF')
if find_key != None:
writer.writerow(find_key)
毫不奇怪,您的输出CSV为空白,或者为您输入的CSV的每一行都包含一个换行符。
以下是问题所在:
find_key = find(row[3], '/home/ro/Desktop/search/IDBUF')
在您的示例中row[3]
求值,'linux'
您将找到名称完全相同的文件'linux'
。如果要查找所有可以使用名称的文件,'linux01.jpg'
或'linuximg.jpg'
将上一行更改为:
find_key = find('*' + row[3] + '*', '/home/ro/Desktop/search/IDBUF')
另一种解决方案是编写*linux*
而不是linux
在输入的CSV文件中编写。
希望这可以帮助 !
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句