gpt4 book ai didi

python - 获取更改当前工作目录后所有 ".txt"的文件列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:11 24 4
gpt4 key购买 nike

我更改了当前工作目录,然后我想列出该目录中扩展名为 .txt 的所有文件。我怎样才能做到这一点?

# !/usr/bin/python

import os

path = "/home/pawn/Desktop/projects_files"
os.chdir(path)

## checking working directory
print ("working directory "+ os.getcwd()+'\n')

现在如何列出当前目录(projects_files)中扩展名为.txt的所有文件?

最佳答案

使用glob ,这是文件的通配符搜索,您也不需要更改目录:

import glob

for f in glob.iglob('/home/pawn/Desktop/project_files/*.txt'):
print(f)

关于python - 获取更改当前工作目录后所有 ".txt"的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com