根据python中的条件从文件夹中读取CSV文件

发布于 2025-02-06 22:47:09 字数 327 浏览 2 评论 0原文

我想根据条件从文件夹中读取CSV文件。我只想阅读文件名中包含“ 1441”的CSV文件。我使用了FNMatch,但它不起作用。谁能帮忙?

path_to_parent = r"C:\Users\Desktop\books/chapter_1"

for csv_file in os.listdir(path_to_parent):
    if fnmatch.fnmatch(csv_file,'1441'):
        my_file = pd.read_csv(path_to_parent+csv_file)
    else:
        print('error')

I want to read csv files from a folder based on condition. I just want to read csv files that include “1441” in the filename. I used fnmatch, but it doesn’t work. Can anyone help?

path_to_parent = r"C:\Users\Desktop\books/chapter_1"

for csv_file in os.listdir(path_to_parent):
    if fnmatch.fnmatch(csv_file,'1441'):
        my_file = pd.read_csv(path_to_parent+csv_file)
    else:
        print('error')

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

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

发布评论

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

评论(2

拒绝两难 2025-02-13 22:47:09

您需要围绕1441的通配符来匹配文件名的其余部分。否则,它正在寻找确切的文件名1441

另外,您不会在path_to_parentcsv_file之间添加目录分离器。最好将os.path.join()用于便携性。

for csv_file in os.listdir(path_to_parent):
    if fnmatch.fnmatch(csv_file,'*1441*'):
        my_file = pd.read_csv(os.path.join(path_to_parent, csv_file))
    else:
        print('error')

我还建议您改用glob.glob()。它将为您提供通配符匹配,并且会返回完整的路径,因此您不必每次通过循环进行连接。

for csv_file in glob.glob(os.path.join(path_to_parent, '*1441*')):
    my_file = pd.read_csv(csv_file)

You need wildcards around 1441 to match the rest of the filename. Otherwise it's looking for the exact filename 1441.

Also, you're not adding the directory separator between path_to_parent and csv_file when you concatenate them. It's best to use os.path.join() for portability.

for csv_file in os.listdir(path_to_parent):
    if fnmatch.fnmatch(csv_file,'*1441*'):
        my_file = pd.read_csv(os.path.join(path_to_parent, csv_file))
    else:
        print('error')

I also recommend using glob.glob() instead. It will do the wildcard matching for you, and it will return full paths so you don't have to concatenate each time through the loop.

for csv_file in glob.glob(os.path.join(path_to_parent, '*1441*')):
    my_file = pd.read_csv(csv_file)
万劫不复 2025-02-13 22:47:09

您可以尝试使用不同的方法对您的if语句进行稍作修改。

for csv_file in os.listdir(path_to_parent):
        if '1441' in csv_file:
            my_file = pd.read_csv(f'{path_to_parent}/{csv_file}')
        else:
            print('error')

You could try different approach with slight modification to your if statement.

for csv_file in os.listdir(path_to_parent):
        if '1441' in csv_file:
            my_file = pd.read_csv(f'{path_to_parent}/{csv_file}')
        else:
            print('error')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文