【问题标题】:Python walk through directory and open a txt filePython遍历目录并打开一个txt文件
【发布时间】:2016-12-20 23:06:26
【问题描述】:

我正在尝试使用 saprql 查询打开和处理我从维基百科下载的数千个文本文件。我使用以下代码:

list_words=[]
for roots, dirs, files in os.walk(path):
    for file in files:
        if file.endswith(".txt"):
           with open(file, 'r') as f:
                content= f.read()

                #remove the punct
                table=string.maketrans(string.punctuation,' '*len(string.punctuation)) 
                s= content.translate(table)


                #remove the stopwords
                text= ' '.join([word for word in s.split() if word not in stopwords])
                alfa= " ".join(text.split())

                #remove the verbs
                for word, pos in tag(alfa): # trovo tutti i verbi.
                    if pos != "VB": 
                        lower= word.lower()
                        lower_2= unicode(lower, 'utf-8', errors='ignore')
                        list_words.append(lower_2)

                #remove numbers 
                testo_2 = [item for item in list_words if not item.isdigit()]

print set(list_words)           

问题是脚本打开了一些文本文件,而对于其他文件,它给了我错误:“不是这样的文件或目录:blablabla.txt”

有人知道为什么会这样吗?我该如何应对?

谢谢!

【问题讨论】:

  • 文件路径给出了相对于dirpath的文件名,如果文件不在工作目录中,则找不到。

标签: python list file os.walk


【解决方案1】:

file 是相对的,您必须将根目录和文件连接起来才能获得绝对文件名,如下所示:

absolute_filename = os.path.join(roots, file)
with open(absolute_filename, 'r') as f:
   .... rest of code

(应该命名为root而不是roots)。

【讨论】:

  • 嘿,安东尼!我正在按照您的步骤操作,但我发现它给了我同样的问题:
  • 嘿,安东尼!我按照您的步骤操作,但它给了我同样的问题... IOError: [Errno 2] No such file or directory: 'C:\\Users\\Cosimo\\Desktop\\Tirocinio\\progetto_arianna\\Sintesi H2O_txt\ \sintesi_txt\\1000testi\\Andrej Aleksandrovic Mironov.txt
  • 看起来真的很奇怪!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 2020-07-02
相关资源
最近更新 更多