如何使用 Python 在文本文件中保存文件名及其目录路径

How to Save file names and their directories path in a text file using Python

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

请帮忙,我对编码和 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.'

如果您要查找字典,请不要进行字符串比较。而是使用 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)

这应该将输出写入 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))