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

时间:2016-07-26 02:48:33

标签: python string-comparison file-comparison

我正在尝试查找目录下的文件中包含的字符串。然后使它将文件名和目录存储在新的文本文件下。 我到达了目录并查找字符串,然后打印结果。但不确定下一步。

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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))