遍历相对路径中的多个文件名



我试图遍历位于相对路径中的所有.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从文件名中剥离路径。看到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.

如果你想要base名w/o .txt扩展名,那么使用Path.stem();例如path/Alice.txt =>爱丽丝。

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

最新更新