地球模式:仅从顶部目录中排除文件

发布于 2025-01-31 21:50:51 字数 524 浏览 2 评论 0原文

让我们以下面的示例为我的文件夹结构,

|---GCD.txt
|---Azure.png
|---AWS.txt
|---foo/
|     |--- app.txt
|     |--- bar.txt

gcd.txt,azure.png,aws.txt 文件位于根文件夹。我不知道文件夹名称(每次新的GUID)。

现在,我想编写一个地球模式,以便仅从根文件夹中只能跳过文本文件(*。txt),而不是从子文件夹中跳过。因此,应该跳过预期的行为,

|---Azure.png
|---foo/
|     |--- app.txt
|     |--- bar.txt

gcd.txt aws.txt

我的尝试:

.*.txt
./*.txt
*.txt

上述模式没有任何帮助。我错过了什么吗?

Lets take a below example as my folder structure,

|---GCD.txt
|---Azure.png
|---AWS.txt
|---foo/
|     |--- app.txt
|     |--- bar.txt

GCD.txt, azure.png, AWS.txt files are at root folder. I don't know the folder name(New GUID every time).

Now I want to write a glob pattern such that text file(*.txt) only from root folder should skip, not from sub-folders. So expected behavior should be,

|---Azure.png
|---foo/
|     |--- app.txt
|     |--- bar.txt

GCD.txt and AWS.txt should be skipped.

My attempts:

.*.txt
./*.txt
*.txt

None of the above pattern helped. Am I missing something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞笑我太脆弱 2025-02-07 21:50:51

我认为没有一个可以传递给Glob的表达可以做到这一点。但是,这就是可以做到的:

from os import walk
from os.path import join
from pathlib import Path

files_of_interest = []
base_directory = '.'

def istxt(filename):
    return Path(filename).suffix.lower() in {'.txt'}

for root, _, files in walk(base_directory):
    if root == base_directory:
        for file in files:
            if not istxt(file):
                files_of_interest.append(join(root, file))
    else:
        for file in files:
            if istxt(file):
                files_of_interest.append(join(root, file))

print(files_of_interest)

I don't think there's an expression that can be passed to glob that will do this. Here's how it could be done though:

from os import walk
from os.path import join
from pathlib import Path

files_of_interest = []
base_directory = '.'

def istxt(filename):
    return Path(filename).suffix.lower() in {'.txt'}

for root, _, files in walk(base_directory):
    if root == base_directory:
        for file in files:
            if not istxt(file):
                files_of_interest.append(join(root, file))
    else:
        for file in files:
            if istxt(file):
                files_of_interest.append(join(root, file))

print(files_of_interest)
So要识趣 2025-02-07 21:50:51

要匹配每个文件,除了root上的文件与扩展名“ .txt”之外,您可以使用以下环境模式:

!*.txt

用作“不”,因此基本上说“不匹配任何文件*.txt结尾的“ ”。

(这是一个较晚的答案,但我希望它仍然可以帮助可能落在此页面上的其他人。)

To match every file, except files on root with extension ".txt", you can use the following glob pattern:

!*.txt

The ! acts as a "NOT", so it basically says "Do NOT ! match any file * that ends with .txt".

(It's a late answer, but I hope it can still help other people who might land on this page.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文