How to confirm only html files exist in a given folder and if not then how to prompt the user to specify a folder with only html files within
Question: I would like to create a python script that will do 3 things:

* 1) Take user input to navigate to a file directory
* 2) Confirm the file contents (a particular set of files need to be in the folder for the script to proceed)
* 3) Do a Find and Replace

The Code as of now:

    
    
    import os, time
    from os.path import walk
    
    mydictionary = {"</i>":"</em>"}
    
    for (path, dirs, files) in os.walk(raw_input('Copy and Paste Course Directory Here: ')):
        for f in files:
            if f.endswith('.html'):
                filepath = os.path.join(path,f)
                s = open(filepath).read()
                for k, v in mydictionary.iteritems(): terms for a dictionary file and replace
                    s = s.replace(k, v)
                f = open(filepath, 'w')
                f.write(s)
                f.close()
    

Now i Have parts 1 and 3, I just need part 2.

for part 2 though I need to confirm that only html files exist in the
directory the the user will specified otherwise the script will prompt the
user to enter the correct folder directory (which will contain html files)

Thanks


Answer: From what I understand, here's your pseudocode:

    
    
    Ask user for directory
    If all files in that directory are .html files:
        Do the search-and-replace stuff on the files
    Else:
        Warn and repeat from start
    

I don't think you actually want a recursive walk here, so first I'll write
that with a flat listing:

    
    
    while True:
        dir = raw_input('Copy and Paste Course Directory Here: ')
        files = os.listdir(dir)
        if all(file.endswith('.html') for file in files):
            # do the search and replace stuff
            break
        else:
            print 'Sorry, there are non-HTML files here. Try again.'
    

Except for having the translate the "repeat from start" into a `while True`
loop with a `break`, this is almost a word-for-word translation from the
English pseudocode.

If you _do_ need the recursive walk through subdirectories, you probably don't
want to write the `all` as a one-liner. It's not that hard to write "all
members of the third member of any member of the `os.walk` result end with
`'.html'`", but it will be hard to read. But if you turn that English
description into something more understandable, you should be able to see how
to turn it directly into code.

