How can I save the search output of files matching * .txt variable?

I am new to python. I would like to save the text that is printed on this script as a variable. (The variable should be written to the file later, if that matters.) How can I do this?

import fnmatch
import os

for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
+2
source share
5 answers

you can save it in a variable as follows:

import fnmatch
import os

for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
        my_var = file
        # do your stuff

or you can save it in a list for later use:

import fnmatch
import os
my_match = []

for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
        my_match.append(file)       # append insert the value at end of list
# do stuff with my_match list
+3
source

You can save it in the list:

import fnmatch
import os

matches = []
for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        matches.append(file)
+3
source

, Python . , .

import fnmatch
import os

matches = [filename for filename in os.listdir("/Users/x/y") if fnmatch.fnmatch(filename, "*.txt")]
+3

, - , ...

def list_ext_in_dir(e,d):
    """e=extension, d= directory => list of matching filenames.
    If the directory d cannot be listed returns None."""

    from fnmatch import fnmatch
    from os import listdir

    try:
        dirlist = os.listdir(d)
    except OSError:
        return None

    return [fname for fname in dirlist if fnmatch(fname,e)]
  • dirlist try except, , (, ..). , ...

  • , , python .

,

l_txtfiles = list_ext_in_dir('*.txt','/Users/x/y;)
+1

NSU , , .

, fnmatch , , glob , . :

os.listdir() fnmatch.fnmatch() ...

, :

import glob
matches = glob.glob("/Users/x/y/*.txt")

, , '/Users/x/y/spam.txt', 'spam.txt', , . os.path.basename , , os.path.join , ... "" "".

Also note that I had to manually insert tags "/Users/x/y/"and "*.txt"a single line, as in the command line. This is good, but if, say, the first of the variables, and not hard-coded into the source code, you have to use os.path.join(basepath, "*.txt"), which is not so nice.

By the way, if you are using Python 3.4 or later, you can get the exact same thing from a higher level pathliblibrary:

import pathlib
matches = list(pathlib.Path("/Users/x/y/").glob("*.txt"))
+1
source

All Articles