该程序的目的是收集计算机上所有程序的列表,并根据用户输入找到正确的路径。因此,如果输入是Audition
程序将返回
C:\Adobe\Audition CC 2014\Audition CC 2014.exe
。
我需要它在 txt 文件中搜索与用户输入的任何内容最相似的行。我的代码如下:
import os
import subprocess
import getpass
import sys
import difflib
from difflib import SequenceMatcher as SM
user = getpass.getuser()
print(os.getcwd())
exeFile = (os.getcwd() + "/paths/programpaths.txt")
def get_filepaths(directory):
file_paths = [] # List which will store all of the full filepaths.
exes = open(os.getcwd() + "/paths/programpaths.txt", "w+")
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
if filepath.endswith('exe') and "ninstall" not in filepath and "$RECYCLE.BIN" not in filepath:
files = filepath.encode('cp850', errors='replace').decode('cp850')
#print(files + "\n")
exes.write(files + "\n")
return file_paths # Self-explanatory.
if not os.path.exists(exeFile):
print("List compilation should only happen once")
print()
print("Compiling list of installed programs")
print("This may take a while")
exes = open(os.getcwd() + "/paths/programpaths.txt", "a+")
full_file_pathsx64 = get_filepaths('C:\Program Files')
full_file_pathsx86 = get_filepaths('C:\Program Files (x86)')
full_file_pathsgames = get_filepaths('G:\\')
# Run the above function and store its results in a variable.
print("List compilation should only happen once")
print()
print("Done!")
pinput = input()
for line in open(exeFile):
prog = line.split("\\")[-1]
sim = difflib.get_close_matches(pinput, [prog], 1)
print(sim)
但是,这会为文件中的每一行打印一个空白括号“[]”,而不仅仅是给我我需要的那个。
我知道这是因为我告诉它对每一行都这样做,但我不知道如何解决这个问题。