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

射线

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

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

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

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从文件名中去除路径。请参阅路径库

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.

如果您想要不带 .txt 扩展名的基本名称,请使用 Path.stem(); 例如路径/Alice.txt => Alice。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章