0

So far my code is this :

from glob import glob
shakedir='D:\report\shakeall'
from shakedir import isfile
def countwords(fp):
   with open(fp) as fh:
       return len(fh.read().split())
print "There are" ,sum(map(countwords, filter(isfile, glob("*.txt") ) ) ), "words in the files."

The problem is this code doesn't work :)

I'm not used to Python grammar, so I just tried anything.

What I want is, I want this script to import text files from specific directory.

Not from the os.path, where my .py file is.

I want to import from D:\report\shakeall and I can't. That's it.

Thanks for any advice.

2

4 Answers 4

1

You can also use glob function alone for this purpose:

from glob import glob

pattern = "D:\\report\\shakeall\\*.txt"
filelist = glob(pattern)

and then do whatever you want on that filelist. Your way should work now:

def countwords(fp):
    with open(fp) as fh:
        return len(fh.read().split())

print "There are" ,sum(map(countwords, filelist))), "words in the files."
Sign up to request clarification or add additional context in comments.

Comments

0

You can use os.walk("pathname") to get a list of files in a certain directory. http://docs.python.org/library/os#os.walk

Comments

0

If I understand your question correctly, what you need is:

shakedir = "d:\\report\\shakeall"
..
print "There are" ,sum(map(countwords, filter(isfile, glob(shakedir + "\\*.txt"))))), ".."
                                                           ^^^^^ It can take directories too..

The line:

from shakedir import isfile

does not make any sense to me. And provide an implementation for isfile, or use the one from os module.

1 Comment

umm..what I just wanted to import files from that directory and simply did in that way. sorry for that.
0

backslashes signify an escape in a string literal. Try either

"d:/report/shakeall"

Or

"d:\\report\\shakeall"

Ideally:

os.path.join("d:", "report/", "shakeall")

1 Comment

Or a raw string - r"d:\report"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.