如何使用Python在目錄中找出沒有擴展名的檔案

2024-04-24 14:48:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些文件在一个没有任何扩展名的目录中,我想知道如何搜索这些文件并添加.txt作为扩展名?在

有更好的方法吗?在

    for file in found:

          fileExt = os.path.splitext(file)[-1]
          if '' == fileExt:
              print 'Found No Ext %s' %file

Tags: 文件path方法in目录txtforif
1条回答
网友
1楼 · 发布于 2024-04-24 14:48:15

您只需list目录中的所有文件,然后rename它们:

dirname = '/some/directory'
for f in os.listdir(dirname):
    path = os.path.join(dirname, f)
    if not os.path.isfile(path):
        continue  # A directory or some other weird object
    if not os.path.splitext(f)[1]:
        os.rename(path, path + '.txt')

相关问题 更多 >