迭代相对路径中的多个文件名

Iterate Over Multiple Filenames in Relative Path

我正在尝试遍历位于相对路径中的所有 .txt 文件名。 (在我的 Mac 上,如果没有相对路径,即使 .py 文件与 .txt 文件位于同一目录中,我也无法使它工作) 我'我使用了以下内容:

import os
path_str = "Chapter 10_Files_Exceptions/*.txt"

当我遍历名为文件名的列表中的每个文件名时....

filenames = ['Chapter 10_Files_Exceptions/alice.txt', 'Chapter 10_Files_Exceptions/siddhartha.txt', 
            'Chapter 10_Files_Exceptions/moby_dick.txt', 'Chapter 10_Files_Exceptions/little_women.txt'
            ]

for filename in filenames:
    count_words(filename)

我得到这个结果...

*.txt has 29465 within it.
*.txt has 42172 within it.
*.txt has 215830 within it.
*.txt has 189079 within it.

*如何执行此操作并让每个文件名显示而不是 .txt?

import os
path_str = "Chapter 10_Files_Exceptions/*.txt"

def count_words(filename):
    """Count the approximate number of words in a file."""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"{os.path.basename(path_str).capitalize()} is not located in your current working directory.")
    else:
        words = contents.split()
        num_words = len(words)
        print(f"{os.path.basename(path_str).capitalize()} has {num_words} within it.")

filenames = ['Chapter 10_Files_Exceptions/alice.txt', 'Chapter 10_Files_Exceptions/siddhartha.txt', 
            'Chapter 10_Files_Exceptions/moby_dick.txt', 'Chapter 10_Files_Exceptions/little_women.txt'
            ]

for filename in filenames:
    count_words(filename)

使用Path(filename).name从文件名中去除路径。参见 pathlib

from pathlib import Path

def count_words(filename):
   name = Path(filename).name.capitalize()
   ...
   else:
        words = contents.split()
        num_words = len(words)
        print(f"{name} has {num_words} within it.")

输出:

Alice.txt has 29465 within it.
Siddhartha.txt has 42172 within it.
Moby_dick.txt has 215830 within it.
Little_women.txt has 189079 within it.

如果您想要基本名称 w/o .txt 扩展名,请使用 Path.stem();例如path/Alice.txt => 爱丽丝.

name = Path(filename).stem.capitalize()