.Txt දිගුව සහිත බහලුමක ඇති සියලුම ලිපිගොනු පයිතන්හි සොයා ගන්න


1043

.txtපයිතන් හි දිගුවක් ඇති නාමාවලියක ඇති සියලුම ලිපිගොනු සොයා ගන්නේ කෙසේද ?

Answers:


2444

ඔබට භාවිතා කළ හැකිය glob:

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

හෝ සරලව os.listdir:

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

හෝ ඔබට නාමාවලිය හරහා ගමන් කිරීමට අවශ්‍ය නම්, භාවිතා කරන්න 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))

11
විසඳුම # 2 භාවිතා කරමින්, ඔබ එම තොරතුරු සමඟ ගොනුවක් හෝ ලැයිස්තුවක් නිර්මාණය කරන්නේ කෙසේද?
මර්ලින්

74
@ ghostdog74: විචල්යයේ ඇති දේ තනි ගොනු නාමයක් බැවින් ලිවීමට for file in fවඩා සුදුසු යැයි මගේ මතයයි for files in f. ඊටත් වඩා හොඳ වනුයේ වෙනස් fකිරීම filesසහ පසුව ලූප බවට පත්වීමයි for file in files.
මාර්ටිනෝ

47
putcomputermacgyver: නැත, fileවෙන් කර ඇති වචනයක් නොවේ, එය පෙර නියම කළ ශ්‍රිතයක නම පමණි, එබැවින් එය ඔබේම කේතයේ විචල්‍ය නාමයක් ලෙස භාවිතා කළ හැකිය. සාමාන්‍යයෙන් යමෙකු එවැනි ගැටුම් වලින් වැළකී සිටිය යුතු බව සත්‍යයක් වුවද, එය fileවිශේෂ අවස්ථාවක් වන්නේ එය භාවිතා කිරීමේ අවශ්‍යතාවයක් නැති තරම්ය, එබැවින් එය බොහෝ විට මාර්ගෝපදේශයට ව්‍යතිරේකයක් ලෙස සලකනු ලැබේ. ඔබට එය කිරීමට අවශ්‍ය නැතිනම්, PEP8 එවැනි නම් සඳහා එක් අවධාරනයක් එකතු කිරීමට නිර්දේශ කරයි, එනම් file_, ඔබ එකඟ විය යුතු තවමත් කියවිය හැකි ය.
මාර්ටිනෝ

9
ස්තූතියි, මාර්ටිනෝ, ඔබ ඇත්තෙන්ම හරි. මම ඉක්මණින් නිගමනවලට පැන්නෙමි.
Computermacgyver

42
# 2 සඳහා වඩාත් Pythonic ක්රමයක් විය හැක [( '/ mydir') f.endswith ( '. Txt') නම් os.listdir දී f සඳහා f] ගොනුව සඳහා:
ozgur

259

ග්ලෝබ් භාවිතා කරන්න .

>>> import glob
>>> glob.glob('./*.txt')
['./outline.txt', './pip-log.txt', './test.txt', './testingvim.txt']

මෙය පහසු වනවා පමණක් නොව, එයද සංවේදී නොවේ. (අවම වශයෙන් එය වින්ඩෝස් වල තිබිය යුතුය. වෙනත් මෙහෙයුම් පද්ධති ගැන මට විශ්වාස නැත.)
ජෝන් කුම්බ්ස්

35
ඔබේ පයිතන් 3.5 ට අඩු නම් නැවත නැවතglob ලිපිගොනු සොයාගත නොහැකි බවට පරිස්සම් වන්න . වැඩි විස්තර
qun

හොඳම කොටස නම් ඔබට නිත්‍ය ප්‍රකාශන පරීක්ෂණය භාවිතා කළ හැකිය * .txt
ඇලෙක්ස් පුන්නන්

On ජෝන්කොම්බ්ස් නැත. අවම වශයෙන් ලිනක්ස් මත නොවේ.
කරුහංග

163

ඒ වගේ දෙයක් කළ යුතුයි

for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file

75
ඔබේ විචල්‍යයන් root, dirs, filesවෙනුවට නම් කිරීම සඳහා +1 r, d, f. තවත් බොහෝ දේ කියවිය හැකිය.
ක්ලෙමන්ට්

30
:. මෙම, ඔබට මීට file.lower () endswith ( '. Txt') නම් කරන්න අවශ්ය වනු පිණිස, නඩුව සංවේදී (.txt හෝ .txt නොගැලපේ) බව සටහන
ජෝන් Coombs

1
ඔබේ පිළිතුර උප බහලුම සමඟ කටයුතු කරයි.
සෑම් ලියාඕ

121

මේ වගේ දෙයක් ක්‍රියාත්මක වේ:

>>> 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']

පෙළ_ ලිපිගොනු වෙත මාවත සුරැකෙන්නේ කෙසේද? ['path / euc-cn.txt', ... 'path / windows-950.txt']
IceQueeny

6
os.path.joinහි එක් එක් මූලද්රව්ය මත ඔබට භාවිතා කළ හැකිය text_files. එය වැනි දෙයක් විය හැකිය text_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.txt')].
සෙත්

64

ඔබට සරලවම pathlibs 1 භාවිතා කළ හැකිය :glob

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

හෝ පුඩුවක් තුළ:

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

ඔබට එය පුනරාවර්තන අවශ්‍ය නම් ඔබට භාවිතා කළ හැකිය .glob('**/*.txt)


1 මෙම pathlibමොඩියුලය පිඹුරා 3.4 සම්මත පුස්තකාලය ඇතුළත් කරන ලදී. නමුත් පැරණි පයිතන් අනුවාදවල (එනම් භාවිතා කිරීම condaහෝ භාවිතා කිරීම pip) පවා ඔබට එම මොඩියුලයේ පසු-වරායන් ස්ථාපනය කළ හැකිය : pathlibසහ pathlib2.


**/*.txtපැරණි පයිතන් අනුවාදයන් සඳහා සහය නොදක්වයි. එබැවින් මම මෙය විසඳුවේ: foundfiles= subprocess.check_output("ls **/*.txt", shell=True) for foundfile in foundfiles.splitlines(): print foundfile
රෝම

1
Oman රෝමන් ඔව්, එය pathlibකළ හැකි දේ ප්‍රදර්ශකයක් පමණක් වන අතර මම දැනටමත් පයිතන් අනුවාද අවශ්‍යතා ඇතුළත් කර ඇත්තෙමි. :) නමුත් ඔබේ ප්‍රවේශය දැනටමත් පළ කර නොමැති නම් එය වෙනත් පිළිතුරක් ලෙස එකතු නොකරන්නේ ඇයි?
MSeifert

1
ඔව්, පිළිතුරක් පළ කිරීමෙන් මට වඩා හොඳ හැඩතල ගැන්වීමේ හැකියාවක් ලැබෙනු ඇත. මම එය එහි පළ කරන්නේ මෙය වඩාත් සුදුසු ස්ථානයක් යැයි මා සිතන බැවිනි.
රෝම

6
ඔබට rglobනැවත නැවත අයිතම සෙවීමට අවශ්‍ය නම් ඔබට භාවිතා කළ හැකි බව සලකන්න . උදා.rglob('*.txt')
බ්‍රැම් වැන්රෝයි

43
import os

path = 'mypath/path' 
files = os.listdir(path)

files_txt = [i for i in files if i.endswith('.txt')]

31

තරමක් වෙනස් ප්‍රති results ල ලබා දෙන එකම අනුවාදයන් මෙන්න:

glob.iglob ()

import glob
for f in glob.iglob("/mydir/*/*.txt"): # generator, search immediate subdirectories 
    print f

glob.glob1 ()

print glob.glob1("/mydir", "*.tx?")  # literal_directory, basename_pattern

fnmatch.filter ()

import fnmatch, os
print fnmatch.filter(os.listdir("/mydir"), "*.tx?") # include dot-files

3
කුතුහලය දනවන glob1()කාරණය නම් glob, පයිතන් ප්‍රලේඛනයේ ලැයිස්තුගත කර නොමැති මොඩියුලයේ සහායක ශ්‍රිතයකි . ප්‍රභව ගොනුවේ එය කරන්නේ කුමක්ද යන්න විස්තර කරන පේළි කිහිපයක් තිබේ, බලන්න .../Lib/glob.py.
මාර්ටිනෝ

1
art මාර්ටිනෝ: glob.glob1()පොදු නොවන නමුත් එය පයිතන් 2.4-2.7; 3.0-3.2; pypy; jython github.com/zed/test_glob1
jfs

1
ස්තූතියි, මොඩියුලයක ලේඛනගත නොකළ පෞද්ගලික ශ්‍රිතයක් භාවිතා කළ යුතුද යන්න තීරණය කිරීමේදී එය සතුව ඇති අමතර අමතර තොරතුරු වේ. ;-) මෙන්න තව ටිකක්. පයිතන් 2.7 අනුවාදය දිග පේළි 12 ක් පමණක් වන අතර එය පහසුවෙන් globමොඩියුලයෙන් උකහා ගත හැකි බව පෙනේ .
මාර්ටිනෝ

31

මම os.walk () වලට කැමතියි :

import os

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

හෝ ජනක යන්ත්‍ර සමඟ:

import os

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)

22

path.py තවත් විකල්පයකි: https://github.com/jaraco/path.py

from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
    print f

සිසිල්, එය රටාවේ නිත්‍ය ප්‍රකාශනය ද පිළිගනී. මම for f in p.walk(pattern='*.txt')සෑම උප ෆෝල්ඩරයක්
හරහාම ගමන් කරමි

1
යාත්පාද ඇත. ඔබට මෙවැනි දෙයක් කළ හැකිය: list(p.glob('**/*.py'))
user2233949

18

පයිතන් v3.5 +

පුනරාවර්තන ශ්‍රිතයක os.scandir භාවිතා කරන වේගවත් ක්‍රමය. ෆෝල්ඩරයේ සහ උප ෆෝල්ඩරවල නිශ්චිත දිගුවක් සහිත සියලුම ලිපිගොනු සෙවීම.

import os

def findFilesInFolder(path, pathList, extension, subFolders = True):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:        Base directory to find files
    pathList:    A list that stores all paths
    extension:   File extension to find
    subFolders:  Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    """

    try:   # Trapping a OSError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and entry.path.endswith(extension):
                pathList.append(entry.path)
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                pathList = findFilesInFolder(entry.path, pathList, extension, subFolders)
    except OSError:
        print('Cannot access ' + path +'. Probably a permissions error')

    return pathList

dir_name = r'J:\myDirectory'
extension = ".txt"

pathList = []
pathList = findFilesInFolder(dir_name, pathList, extension, True)

2019 අප්‍රේල් යාවත්කාලීන කරන්න

10,000 ක ලිපිගොනු අඩංගු නාමාවලි හරහා ඔබ සොයන්නේ නම්, ලැයිස්තුවකට එකතු කිරීම අකාර්යක්ෂම වේ. ප්‍රති ields ල 'අස්වැන්න' වඩා හොඳ විසඳුමකි. ප්‍රතිදානය පැන්ඩාස් දත්ත රාමුවකට පරිවර්තනය කිරීමේ ශ්‍රිතයක් ද මම ඇතුළත් කර ඇත්තෙමි.

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]

    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .

    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 

                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]

                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path

            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """

    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })

    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

14

මේ සඳහා පයිතන්ට සියලු මෙවලම් තිබේ:

import os

the_dir = 'the_dir_that_want_to_search_in'
all_txt_files = filter(lambda x: x.endswith('.txt'), os.listdir(the_dir))

1
All_txt_files ලැයිස්තුවක් වීමට ඔබට අවශ්‍ය නම්:all_txt_files = list(filter(lambda x: x.endswith('.txt'), os.listdir(the_dir)))
Ena

14

'ඩේටාපාත්' ෆෝල්ඩරය තුළ ඇති සියලුම '.txt' ගොනු නාමයන් පයිතොනික් ආකාරයෙන් ලැයිස්තුවක් ලෙස ලබා ගැනීම සඳහා:

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles

14

මෙය උත්සාහ කරන්න මෙය ඔබගේ සියලුම ලිපිගොනු පුනරාවර්තන ලෙස සොයා ගනු ඇත:

import glob, os
os.chdir("H:\\wallpaper")# use whatever directory you want

#double\\ no single \

for file in glob.glob("**/*.txt", recursive = True):
    print(file)

1
පුනරාවර්තන අනුවාදය සමඟ නොවේ (ද්විත්ව තරුව :) **. පයිතන් 3 හි පමණක් ලබා ගත හැකිය. මා අකමැති දෙය chdirකොටසයි. ඒ සඳහා අවශ්‍යතාවයක් නැත.
ජීන්-ප්‍රංශුවා ෆැබ්රේ

2
හොඳයි, ඔබට ඕඑස් පුස්තකාලය මාර්ගයට සම්බන්ධ වීමට භාවිතා කළ හැකිය, උදා, filepath = os.path.join('wallpaper')ඉන්පසු එය භාවිතා කරන්න glob.glob(filepath+"**/*.psd", recursive = True), එමඟින් එකම ප්‍රති .ලය ලැබෙනු ඇත.
මිටලී රාඕ

සුරකින ලද වර්ග නාම සමඟ ගැටෙන්නේ නැති fileදෙයක් සඳහා පැවරුම නැවත නම් කළ යුතු බව සලකන්න_file
gbarnett

9

නිශ්චිත දිගුවක් සහිත ලිපිගොනු සඳහා සම්පූර්ණ ගොනු මාර්ග ලැයිස්තුවක් ලබා ගැනීම සඳහා එක් ෆෝල්ඩරයකට වේගවත්ම විසඳුම කුමක්දැයි උප බහලුම් නොමැතිදැයි බැලීමට මම (පයිතන් 3.6.4, W7x64) පරීක්‍ෂණයක් කළෙමි.

එය කෙටි කිරීමට, මෙම කාර්යය සඳහා os.listdir() වේගවත්ම වන අතර ඊළඟ හොඳම දේ os.walk()මෙන් pathlib1.7x වේගවත් වේ : (විවේකයක් සහිතව!), 2.7x තරම් වේගවත් , 3.2x වේගවත්os.scandir() හා 3.3x වේගවත් glob.
ඔබට මතක තබා ගන්න, ඔබට පුනරාවර්තන ප්‍රති .ල අවශ්‍ය වූ විට එම ප්‍රති results ල වෙනස් වන බව. ඔබ පහත එක් ක්‍රමයක් පිටපත් කර අලවන්නේ නම්, කරුණාකර .lower () වෙනත් ආකාරයකින් එක් කරන්න. .Ext සෙවීමේදී EXT සොයාගත නොහැක.

import os
import pathlib
import timeit
import glob

def a():
    path = pathlib.Path().cwd()
    list_sqlite_files = [str(f) for f in path.glob("*.sqlite")]

def b(): 
    path = os.getcwd()
    list_sqlite_files = [f.path for f in os.scandir(path) if os.path.splitext(f)[1] == ".sqlite"]

def c():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(".sqlite")]

def d():
    path = os.getcwd()
    os.chdir(path)
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob("*.sqlite")]

def e():
    path = os.getcwd()
    list_sqlite_files = [os.path.join(path, f) for f in glob.glob1(str(path), "*.sqlite")]

def f():
    path = os.getcwd()
    list_sqlite_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".sqlite"):
                list_sqlite_files.append( os.path.join(root, file) )
        break



print(timeit.timeit(a, number=1000))
print(timeit.timeit(b, number=1000))
print(timeit.timeit(c, number=1000))
print(timeit.timeit(d, number=1000))
print(timeit.timeit(e, number=1000))
print(timeit.timeit(f, number=1000))

ප්රතිපල:

# Python 3.6.4
0.431
0.515
0.161
0.548
0.537
0.274

පයිතන් 3.6.5 ප්‍රලේඛනයෙහි මෙසේ සඳහන් වේ: os.scandir () ශ්‍රිතය ගොනු නාම තොරතුරු සමඟ නාමාවලි ඇතුළත් කිරීම් ලබා දෙයි, බොහෝ පොදු භාවිත අවස්ථා සඳහා [os.listdir () ට වඩා හොඳ කාර්ය සාධනයක් ලබා දෙයි.
බිල් ඕල්ඩ්රොයිඩ්

මෙම පරීක්ෂණයෙහි ඔබ කොපමණ ප්‍රමාණයක් භාවිතා කර ඇත්ද? ඔබ අංකය ඉහළට / පහළට පරිමාණය කළහොත් ඒවා සංසන්දනය කරන්නේ කෙසේද?
N4ppeL

8
import os
import sys 

if len(sys.argv)==2:
    print('no params')
    sys.exit(1)

dir = sys.argv[1]
mask= sys.argv[2]

files = os.listdir(dir); 

res = filter(lambda x: x.endswith(mask), files); 

print res

5

මෙම කේතය මගේ ජීවිතය සරල කරයි.

import os
fnames = ([file for root, dirs, files in os.walk(dir)
    for file in files
    if file.endswith('.txt') #or file.endswith('.png') or file.endswith('.pdf')
    ])
for fname in fnames: print(fname)


5

එකම ඩිරෙක්ටරියේම "දත්ත" නම් ෆෝල්ඩරයකින් ".txt" ගොනු නාමයන් ලබා ගැනීම සඳහා මම සාමාන්‍යයෙන් මෙම සරල කේත රේඛාව භාවිතා කරමි:

import os
fileNames = [fileName for fileName in os.listdir("data") if fileName.endswith(".txt")]

3

Fnmatch සහ ඉහළ ක්‍රමය භාවිතා කිරීමට මම ඔබට යෝජනා කරමි . මේ ආකාරයෙන් ඔබට පහත සඳහන් ඕනෑම දෙයක් සොයාගත හැකිය:

  1. නම. txt ;
  2. නම. TXT ;
  3. නම. Txt

.

import fnmatch
import os

    for file in os.listdir("/Users/Johnny/Desktop/MyTXTfolder"):
        if fnmatch.fnmatch(file.upper(), '*.TXT'):
            print(file)

3

මෙන්න එකක් සමඟ extend()

types = ('*.jpg', '*.png')
images_list = []
for files in types:
    images_list.extend(glob.glob(os.path.join(path, files)))

භාවිතය සඳහා නොවේ .txt:)
එෆ්‍රීටෝ

2

උප නාමාවලි සමඟ ක්‍රියාකාරී විසඳුම:

from fnmatch import filter
from functools import partial
from itertools import chain
from os import path, walk

print(*chain(*(map(partial(path.join, root), filter(filenames, "*.txt")) for root, _, filenames in walk("mydir"))))

15
මෙම කේතය ඔබට දිගු කාලීනව පවත්වා ගැනීමට අවශ්‍යද?
සිමියොන් වීසර්

2

ෆෝල්ඩරයේ ලිපිගොනු විශාල ප්‍රමාණයක් හෝ මතකයක් අවහිරතාවයක් තිබේ නම්, ජනක යන්ත්‍ර භාවිතා කිරීම සලකා බලන්න:

def yield_files_with_extensions(folder_path, file_extension):
   for _, _, files in os.walk(folder_path):
       for file in files:
           if file.endswith(file_extension):
               yield file

විකල්පය A: අනුකරණය කරන්න

for f in yield_files_with_extensions('.', '.txt'): 
    print(f)

විකල්පය B: සියල්ල ලබා ගන්න

files = [f for f in yield_files_with_extensions('.', '.txt')]

2

හොස්ට් ඩොග්ට සමාන පිටපත්-ඇලවිය හැකි විසඳුමක්:

def get_all_filepaths(root_path, ext):
    """
    Search all files which have a given extension within root_path.

    This ignores the case of the extension and searches subdirectories, too.

    Parameters
    ----------
    root_path : str
    ext : str

    Returns
    -------
    list of str

    Examples
    --------
    >>> get_all_filepaths('/run', '.lock')
    ['/run/unattended-upgrades.lock',
     '/run/mlocate.daily.lock',
     '/run/xtables.lock',
     '/run/mysqld/mysqld.sock.lock',
     '/run/postgresql/.s.PGSQL.5432.lock',
     '/run/network/.ifstate.lock',
     '/run/lock/asound.state.lock']
    """
    import os
    all_files = []
    for root, dirs, files in os.walk(root_path):
        for filename in files:
            if filename.lower().endswith(ext):
                all_files.append(os.path.join(root, filename))
    return all_files

1

නිශ්චිත දිගුවක් සහිත ගොනු සොයා ගැනීමට පයිතන් ඕඑස් මොඩියුලය භාවිතා කරන්න .

සරල උදාහරණය මෙන්න:

import os

# This is the path where you want to search
path = r'd:'  

# this is extension you want to detect
extension = '.txt'   # this can be : .jpg  .png  .xls  .log .....

for root, dirs_list, files_list in os.walk(path):
    for file_name in files_list:
        if os.path.splitext(file_name)[-1] == extension:
            file_name_path = os.path.join(root, file_name)
            print file_name
            print file_name_path   # This is the full path of the filter file

0

බොහෝ පරිශීලකයින් පිළිතුරු සමඟ os.walkපිළිතුරු ලබා දී ඇති අතර, එයට සියලුම ලිපිගොනු පමණක් නොව සියලුම නාමාවලි සහ උප බහලුම් සහ ඒවායේ ගොනු ඇතුළත් වේ.

import os


def files_in_dir(path, extension=''):
    """
       Generator: yields all of the files in <path> ending with
       <extension>

       \param   path       Absolute or relative path to inspect,
       \param   extension  [optional] Only yield files matching this,

       \yield              [filenames]
    """


    for _, dirs, files in os.walk(path):
        dirs[:] = []  # do not recurse directories.
        yield from [f for f in files if f.endswith(extension)]

# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
    print("-", filename)

නැතහොත් ඔබට විදුලි ජනක යන්ත්‍රයක් අවශ්‍ය නොවන තැනකට:

path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
    matches = (f for f in dirfiles if f.endswith(ext))
    break

for filename in matches:
    print("-", filename)

ඔබ වෙනත් දෙයක් සඳහා තරඟ භාවිතා කිරීමට යන්නේ නම්, උත්පාදක ප්‍රකාශනයකට වඩා එය ලැයිස්තුවක් බවට පත් කිරීමට ඔබට අවශ්‍ය විය හැකිය:

    matches = [f for f in dirfiles if f.endswith(ext)]

-1

forලූප් භාවිතා කිරීමෙන් සරල ක්‍රමයක් :

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")

මෙය වඩාත් සාමාන්‍යකරණය කළ හැකි වුවද.


1
දිගුවක් පරික්ෂා කිරීමේ ඉතා අවිධිමත් ක්‍රමය. අනාරක්ෂිතයි. නම ඉතා කෙටි නම් කුමක් කළ යුතුද? සහ නූල් නොව අක්ෂර ලැයිස්තුවක් භාවිතා කරන්නේ ඇයි?
ජීන්-ප්‍රංශුවා ෆැබ්රේ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.