"使用os.walk()无法遍历Python目录树,因为它显示一个名称未定义"

2024-04-20 13:33:32 发布

您现在位置:Python中文网/ 问答频道 /正文

作为家庭作业的一部分,我必须遍历目录树,看起来手术室步行是最好的选择。我使用cygwin运行python脚本。我要穿过的树的路径是: /cygdrive/c/Users/Kamal/Documents/School/Spring2015/CS410/htmlfiles

在我的代码中,下面是手术室步行()电话:

for dirName, subdirList, fileList in os.walk('/cygdrive/c/Users/Kamal/Documents/School/Spring2015/CS410/htmlfiles'):

但是,当我执行脚本时,会出现以下错误:

^{pr2}$

我很困惑为什么它认为“2015年春天”是不确定的?目录显然存在于我的计算机上给定的路径上

编辑:以下是整个代码,因为有人问:

from bs4 import BeautifulSoup
import os
import shutil

cnt = 0

print "starting..."
for dirName, subdirList, fileList in os.walk('/cygdrive/c/Users/Kamal/Documents/School/Spring2015/CS410/htmlfiles'):
for f in fileList:
    #print the path
    print "Processing " + os.path.abspath(f) + "...\n"

    #open the HTML file
    html = open(f)
    soup  = BeautifulSoup(html)

    #Filter out unwanted stuff
    [s.extract() for s in soup(['style', 'script', '[document]',  'head', 'title'])]
    visible_text = soup.getText()
    visible_text_encoded = visible_text.encode('utf-8')
    visible_text_split = visible_text_encoded.split('\n')
    visible_text_filtered = filter(lambda l: l != '', visible_text_split)

    #Generate the name of the output text file
    outfile_name = 'chaya2_' + str(cnt) + '.txt'

    #Open the output file to write in
    outfile = open(outfile_name, "w")

    #Get the URL of the html file using its Path, write it to the first line
    outfile.write(os.path.relpath(f, '/cygdrive/c/Users/Kamal/Documents/School/') + ' \n')

    #Write the visible text to the 
    for l in visible_text_filtered:
        outfile.write(l+'\n')

    #Done writing, move the output file to the appropriate directory
    shutil.move(os.path.abspath(outfile_name), '/cygdrive/c/Users/Kamal/Documents/School/Spring2015/CS410/txtFiles')

    #Rename the html file 
    html_name = 'chaya2_' + str(cnt) + '.html'
    os.rename(f, html_name)

    #Move the html file to the appropriate directory
    shutil.move(os.path.abspath(html_name), '/cygdrive/c/Users/Kamal/Documents/School/Spring2015/CS410/htmlFilesAfter')

    print html_name  + " converted to " + outfile_name + "\n"

    outfile.close()
    html.close()

    cnt+=1

Tags: thetotextnameinoshtmlusers