0

我正在尝试查找目录下文件中包含的字符串。然后让它将它的文件名和目录存储在一个新的文本文件或其他东西下。我到达了它正在通过目录并找到一个字符串的位置,然后打印一个结果。但不确定下一步。

请帮忙,我对编码和python完全陌生。

import glob, os



#Open a source as a file and assign it as source
source = open('target.txt').read()
filedirectories = []

#locating the source file and printing the directories.
os.chdir("/Users/a1003584/desktop")
for root, dirs, files in os.walk(".", topdown=True):
    for name in files:
        print(os.path.join(root, name))
        if source in open(os.path.join(root, name)).read():
            print 'treasure found.'
4

2 回答 2

0

这应该将输出写入 csv 文件

import csv
import os

with open('target.txt') as infile: source = infile.read()

with open("output.csv", 'w') as fout:
    outfile = csv.writer(fout)
    outfile.writerow("Directory FileName FilePath".split())
    for root, dirnames, fnames in os.walk("/Users/a1003584/desktop", topdown=True):
        for fname in fnames:
            with open(os.path.join(root, fname)) as infile:
                if source not in infile.read(): continue
            outfile.writerow(root, fname, os.path.join(root, fname))
于 2016-07-26T03:08:11.160 回答
0

如果您要查找字典,请不要进行字符串比较。而是使用 json 模块。像这样。

import json
import os

filesFound = []

def searchDir(dirName):
    for name in os.listdir(dirName):
        # If it is a file.
        if os.isfile(dirName+name):
            try:
                fileCon = json.load(dirName+name)
            except:
                print("None json file.")
            if "KeySearchedFor" in fileCon:
                filesFound.append(dirName+name)
        # If it is a directory.
        else:
            searchDir(dirName+name+'/')

# Change this to the directory your looking in. 
searchDir("~/Desktop")
open("~/Desktop/OutFile.txt",'w').write(filesFound)
于 2016-07-26T03:07:09.717 回答