通过扩展名查找文件

Finding a file by extension

我正在尝试在 Python3 的特定目录中查找扩展名为 .desktop 的文件。我尝试了下面的代码片段,但它没有按我想要的那样工作。我希望它是单个字符串值。

import os, fnmatch
desktopfile = configparser.ConfigParser ()
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result
script_tmp_dir = "/tmp/appiload/appinstall" # Geçici dizin (dosyalar burada ayıklanıyor)
desktopfilea=f"{script_tmp_dir}/squashfs-root/{str(find ('*.desktop', f'{script_tmp_dir}/squashfs-root/')}"
print(desktopfilea)
desktopfile.items()

结果:

/tmp/appiload/appinstall/squashfs-root/['/tmp/appiload/appinstall/squashfs-root/helloworld.desktop']

我不太明白你的意思,但我做了一个简单的程序,它会打印所有扩展名为 .desktop 的文件,并将它们保存到 2 个文件中:applications.json 数组和 applications.txt刚写了一个又一个

我还有 2 个版本的程序,一个只打印和保存带扩展名的文件名,另一个打印和保存整个路径。

仅文件名:

import os
import json

strApplications = ""
applications = []
for file in os.listdir(os.path.dirname(os.path.realpath(__file__))):
    if file.endswith(".desktop"):
        applications.append(file)

        with open("applications.json", "w") as f:
            json.dump(applications, f)

        strApplications = strApplications + file + "\n"

        with open("applications.txt", "w") as f:
            f.write(strApplications)

print(strApplications)

完整文件路径:

import os
import json

cwd = os.getcwd()

files = [cwd + "\" + f for f in os.listdir(cwd) if f.endswith(".desktop")]

with open("applications.json", "w") as f:
    json.dump(files, f)

with open("applications.txt", "w") as f:
    f.write("\n".join(files))

print("\n".join(files))

使用 glob.glob 而不是编写函数来完成这项工作。

import os, glob

desktopfile = configparser.ConfigParser ()

script_tmp_dir = "/tmp/appiload/appinstall" # Geçici dizin (dosyalar burada ayıklanıyor)
desktopfilea = glob.glob(f'{script_tmp_dir}/squashfs-root/*.desktop')
# desktopfilea = " ".join(desktopfilea) # Join them in one string, using space as seperator
print(str(desktopfilea))
desktopfile.items()