Pentagon98
Pentagon98

Reputation: 123

Python search for file ending

I wrote a python script to search all .avi file in the current folder, and write their names in a file for later processing.

However I only get an empty file, even if I have a .avi in my folder.

Here's my code:

import sh

f = open("film.txt", "w")

ending = [".avi", ".mp4"]
lsa = sh.ls("-a")
for i in lsa:
    if i in "*.avi":
        print(i, file=f)

f.close()

Upvotes: 1

Views: 4457

Answers (6)

saggzz
saggzz

Reputation: 311

modified the answer of Rain Lee a bit.

1st) define a function:

def search_ending(path, extension):
    for root, dir, filenames in os.walk(path):
        for filename in filenames:
            if os.path.splitext(filename)[-1] == extension:
                yield os.path.join(root, filename)

2nd) call that function and put the results in a list:

ext_list = list(search_pos(os.getcwd(), '.jpg'))

3rd) you could display it

for line in ext_list:
        print('\n'+ line)

Upvotes: 0

200_success
200_success

Reputation: 7582

What if i in "*.avi" is doing is asking "is i a substring of '*.avi'"? That is not a glob-matching operation.

The simplest solution is probably to use glob instead of sh.

for i in glob.glob('*.avi') + glob.glob('*.mp4'):
    …

Upvotes: 1

tennabey
tennabey

Reputation: 293

You can simply use the built in glob module which does exactly what you want:

import glob

with open("film.txt", "w") as f:
    f.write("\n".join(glob.glob("*.avi") + glob.glob("*.mp4")))

glob.glob searches for files that match a certain pattern. If you use what I wrote it will search for files in the current directory which have .avi or .mp4 file extensions

Note the use of a context manager (with open(...)) instead of f = open(...) and f.close(). This is more pythonic.

Also, I used \n joining to skip the for loop.

Upvotes: 1

RickyA
RickyA

Reputation: 16029

file writes should be done like this:

f.write(i)

but you probably also have a problem with if i in "*.avi":

so your code would be

import sh

f = open("film.txt", "w")

ending = [".avi", ".mp4"]
lsa = sh.ls("-a")
for i in lsa:
    for end in ending:
        if i.endswith(end): 
            print("found one {}".format(i))
            f.write(i)
f.close()

And now the nice version:

import glob, itertools
patterns = ["*.avi","*.mp4"]
with open("film.txt", "w") as ofile:
    for fl in itertools.chain.from_iterable(glob.glob(pattern) for pattern in patterns):
        ofile.write(fl + "\n")

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28656

in doesn't do such pattern matching. Assuming i is a string, just use

i.endswith('.avi')

But for gods sake, don't call a string variable i.

Or to check for multiple endings at once (thanks @msvalkon for the reminder):

i.endswith((".avi", ".mp4"))

And you could use Python's glob module which does come with such pattern functionality:

import glob
with open("film.txt", "w") as f:
    for filename in glob.glob("*.avi"):
        print(filename, file=f)

Upvotes: 3

Rain Lee
Rain Lee

Reputation: 531

open file via "with":

with open("film.txt", "w") as f:
    for root, _, files in os.walk(os.getcwd()):
        for file in files:
            if file.endswith((".avi", ".mp4")):
                f.write(file)

Upvotes: 1

Related Questions