我的电脑中有一个文件夹,里面有很多.txt
文件:
file_one.txt --> location = r'C:\Users\User\data\file_one.txt'
file_two.txt --> location = r'C:\Users\User\data\file_two.txt'
file_forty.txt --> location = r'C:\Users\User\data\file_forty.txt'
如何将文件名(不带.txt
部分)变成这样的列表:
list_from_files = ['file_one', 'file_two', 'file_forty']
你可以使用pathlib
1。它有一个专用stem
属性,可以返回不带后缀的文件名:
import pathlib
p = pathlib.Path('.') # current directory, insert your directory here
[x.stem for x in p.glob('*.txt')]
1 pathlib
是Python 3.4+ 中标准库的一部分- 但您可以使用第三方(backport-)包,可在 PyPI 和 conda 上使用,例如pathlib
,pathlib2
如果您有较旧的 Python 版本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句