Find all files in a directory with extension .txt

2018-12-31 03:14发布

How can I find all the files in a directory having the extension .txt in python?

30条回答
春风洒进眼中
2楼-- · 2018-12-31 03:27

Python has all tools to do this:

import os

the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 03:29

I like os.walk():

import os, os.path

for root, dirs, files in os.walk(dir):
    for f in files:
        fullpath = os.path.join(root, f)
        if os.path.splitext(fullpath)[1] == '.txt':
            print fullpath

Or with generators:

import os, os.path

fileiter = (os.path.join(root, f)
    for root, _, files in os.walk(dir)
    for f in files)
txtfileiter = (f for f in fileiter if os.path.splitext(f)[1] == '.txt')
for txt in txtfileiter:
    print txt
查看更多
余生无你
4楼-- · 2018-12-31 03:30

You can try this code

import glob
import os
filenames_without_extension = [os.path.basename(c).split('.')[0:1][0] for c in glob.glob('your/files/dir/*.txt')]
filenames_with_extension = [os.path.basename(c) for c in glob.glob('your/files/dir/*.txt')]
查看更多
牵手、夕阳
5楼-- · 2018-12-31 03:30

A simple method by using for loop :

import os

dir = ["e","x","e"]

p = os.listdir('E:')  #path

for n in range(len(p)):
   name = p[n]
   myfile = [name[-3],name[-2],name[-1]]  #for .txt
   if myfile == dir :
      print(name)
   else:
      print("nops")

Though this can be made more generalised .

查看更多
与风俱净
6楼-- · 2018-12-31 03:31

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
    print(file)

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):
        print(os.path.join("/mydir", file))

or if you want to traverse directory, use os.walk:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))
查看更多
余生无你
7楼-- · 2018-12-31 03:33

Something like this will work:

>>> import os
>>> path = '/usr/share/cups/charmaps'
>>> text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
>>> text_files
['euc-cn.txt', 'euc-jp.txt', 'euc-kr.txt', 'euc-tw.txt', ... 'windows-950.txt']
查看更多
登录 后发表回答