简体   繁体   中英

How to import files from specific directory, not using os.path in Python

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.

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

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

backslashes signify an escape in a string literal. Try either

"d:/report/shakeall"

Or

"d:\\report\\shakeall"

Ideally:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM