【问题标题】:How to Save file names and their directories path in a text file using Python如何使用 Python 在文本文件中保存文件名及其目录路径
【发布时间】:2016-07-26 02:48:32
【问题描述】:

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

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

【问题讨论】:

标签: python string-comparison file-comparison


【解决方案1】:

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

【讨论】:

  • 如果使用 json 模块,到底有什么区别?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2017-04-03
    • 2018-07-28
    • 2022-11-11
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    相关资源
    最近更新 更多