如何忽略已经存在的文件?

发布于 2025-02-08 06:44:40 字数 461 浏览 1 评论 0原文

这就是我所拥有的:

import os

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
if os.path.exists(file_path) == True:
   print('name folders exists')
else:
   for name in names:
      os.makedirs(os.path.join('../database', name))

我希望代码在name列表中创建每个名称的文件夹,如果它们不存在并打印名称文件夹,则存在(如果已经存在)。但是我一直在最后一行中获得file existersError。有人可以告诉我我应该在代码中更改什么以使其以我想要的方式工作?

This is what I have:

import os

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
if os.path.exists(file_path) == True:
   print('name folders exists')
else:
   for name in names:
      os.makedirs(os.path.join('../database', name))

I want the code to create the folders for each name in names list if they do not exist and print name folder exists if they already exist. But I keep getting a FileExistsError on the last line. Can someone tell me what I should change in the code to get it to work in the way I want it to?

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

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

发布评论

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

评论(5

沉鱼一梦 2025-02-15 06:44:40

您出错的地方是第3行。此行不执行您认为会做的事情:

file_path = rf'../database/{names}'

它创建一个字符串,其中所有名称添加为列表。
相反,您可以尝试这样的事情:

import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
base_path = '../database'
for name in names:
    full_path = os.path.join(base_path, name)
    if os.path.exists(full_path):
        print('name folders exists')
    else:
        os.mkdir(full_path)

Where you went wrong was line 3. This line doesn't do what you think it would do:

file_path = rf'../database/{names}'

It creates a single string with all the names added as a list.
Instead, you can try something like this:

import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
base_path = '../database'
for name in names:
    full_path = os.path.join(base_path, name)
    if os.path.exists(full_path):
        print('name folders exists')
    else:
        os.mkdir(full_path)
懒的傷心 2025-02-15 06:44:40

使用新的(在python 3.4-3.5中引入,现在不是新的) pathlib 模块而不是os.path

from pathlib import Path

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
BASE_PATH = Path('../database')

for name in names:
    (BASE_PATH / name).mkdir(exist_ok=True)

pathlib.path.mkdir的文档

如果stect_ok是正确的,file existserror例外将被忽略,但是只有当最后一个路径组件不是现有的非主导文件时。

Use the new (introduced in Python 3.4-3.5, so not that new now) Pathlib module instead of os.path:

from pathlib import Path

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
BASE_PATH = Path('../database')

for name in names:
    (BASE_PATH / name).mkdir(exist_ok=True)

From the documentation of pathlib.Path.mkdir:

If exist_ok is true, FileExistsError exceptions will be ignored, but only if the last path component is not an existing non-directory file.

維他命╮ 2025-02-15 06:44:40

使用尝试/除外块来捕获并忽略这些错误。

例如,

try:
    os.makedirs(os.path.join('../database', name))
except FileExistsError:
    pass

您甚至可以这样重写您的代码:

import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']

for name in names:
    try:
        os.makedirs(os.path.join('../database', name))
    except FileExistsError:
        print('name folders exists')

use a try/except block to catch and ignore these errors.

eg

try:
    os.makedirs(os.path.join('../database', name))
except FileExistsError:
    pass

You could even rewrite your code like this:

import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']

for name in names:
    try:
        os.makedirs(os.path.join('../database', name))
    except FileExistsError:
        print('name folders exists')
清晰传感 2025-02-15 06:44:40

您的file_path变量是错误的。它与您的列表相连../数据库/。您列表的所有元素。结果看起来像这样:

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
print(file_path)
# ../database/['Abby', 'Betty', 'Bella', 'Peter', 'Jack', 'Sonya']

相反,请这样做:

# Import os + define names

for name in names:
    path = rf'../database/{name}'
    if not os.path.exists(path):
        os.mkdir(os.path.join(path))

ps:第3行:如果OS.Path.exists(file_path)== true == true true true不是必需的,因为存在函数返回布尔值。只需执行如果OS.Path.exists(file_path):

Your file_path variable is wrong. It concatenate ../database/ with your list. All elements of your list. The result looks like this:

names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
print(file_path)
# ../database/['Abby', 'Betty', 'Bella', 'Peter', 'Jack', 'Sonya']

Instead, do like this:

# Import os + define names

for name in names:
    path = rf'../database/{name}'
    if not os.path.exists(path):
        os.mkdir(os.path.join(path))

PS: line 3: if os.path.exists(file_path) == True The == True is not necessary because the exists function returns a boolean. Just do if os.path.exists(file_path):

心舞飞扬 2025-02-15 06:44:40

示例,只是查看忽略文件或单词的工作方式:

def save_to_pdf(directory_path):
    modified_files = []
    file_count = 0
    for root, dirs, files in os.walk(directory_path):
        for file_name in files:
            if file_name.endswith(".html"):

                # ignora fisierele care contin 'webinar' in numele lor
                if "webinar" in file_name:
                    print(f"Fișierul {file_name} conține 'webinar' în numele său și va fi ignorat.")
                    continue

                file_path = root + os.sep + file_name
                file_content = read_text_from_file(file_path)

                # ignora fisierele care contin 'https://pastebin.com' in continutul lor
                if "https://pastebin.com" in file_content:
                    print(f"Fișierul {file_name} conține 'https://pastebin.com' în conținutul său și va fi ignorat.")
                    continue

Example, just to see how IGNORE files or words works:

def save_to_pdf(directory_path):
    modified_files = []
    file_count = 0
    for root, dirs, files in os.walk(directory_path):
        for file_name in files:
            if file_name.endswith(".html"):

                # ignora fisierele care contin 'webinar' in numele lor
                if "webinar" in file_name:
                    print(f"Fișierul {file_name} conține 'webinar' în numele său și va fi ignorat.")
                    continue

                file_path = root + os.sep + file_name
                file_content = read_text_from_file(file_path)

                # ignora fisierele care contin 'https://pastebin.com' in continutul lor
                if "https://pastebin.com" in file_content:
                    print(f"Fișierul {file_name} conține 'https://pastebin.com' în conținutul său și va fi ignorat.")
                    continue
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文