2012-08-08 68 views
0

到目前为止,我的代码是这样的:如何从特定的目录中导入文件,不使用os.path中在Python

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

问题是这样的代码不工作:)

我不习惯Python语法,所以我只是尝试了任何东西。

我想要的是,我希望这个脚本从特定目录导入文本文件。

不是从os.path,我的.py文件是。

我想从D:\report\shakeall进口,我不能。而已。

感谢您的任何建议。

+0

我不认为os.path中做什么,你认为它...:S 也 - didnt我已经回答这个问题的吗? http://stackoverflow.com/questions/11842548/how-do-i-count-unique-words-of-text-files-in-specific-directory-with-python/11842758#11842758 – 2012-08-08 12:43:46

+0

可能重复的[I不明白Python中的'from'](http://stackoverflow.com/questions/11865835/i-dont-understand-the-from-in-python) – 2012-08-08 15:55:57

回答

1

您还可以使用glob功能单独用于此目的:

from glob import glob 

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

,然后做你想做的对文件列表。用自己的方式应该现在的工作:

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

print "There are" ,sum(map(countwords, filelist))), "words in the files." 
+0

这正是我想要的。非常感谢:) – rocksland 2012-08-08 13:00:14

+0

@이현빈很酷。请接受答案 – dmytro 2012-08-08 14:56:45

0

反斜杠在一个字符串表示的逃逸。尝试要么

"d:/report/shakeall" 

或者

"d:\\report\\shakeall" 

理想:

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

或者一个原始字符串 - r“d:\ report” – neil 2012-08-08 12:55:34

+0

新鲜指点。谢谢! – rocksland 2012-08-08 13:01:18

0

如果我正确理解你的问题,你需要的是:

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

行:

from shakedir import isfile 

对我没有任何意义。并为isfile提供一个实现,或者使用os模块中的一个。

+0

嗯..我只是想从该目录导入文件,只是以这种方式进行。对不起。 – rocksland 2012-08-08 13:02:55

相关问题