【发布时间】:2015-02-10 04:01:44
【问题描述】:
我写了一个简单的脚本,它在一个文件夹上运行,会循环遍历一个文件夹中的所有文件来做一些处理(实际处理不重要)。
我有一个文件夹。此文件夹包含多个不同的文件夹。在这些文件夹中是可变数量的文件,我想在这些文件上运行我编写的脚本。我正在努力调整我的代码来做到这一点。
所以之前的文件结构是:
Folder
Html1
Html2
Html3
...
现在是:
Folder
Folder1
Html1
Folder2
Html2
Html3
我仍然想在所有 HTML 上运行代码。
这是我这样做的尝试,结果是
error on line 25, in CleanUpFolder
orig_f.write(soup.prettify().encode(soup.original_encoding))
TypeError: encode() argument 1 must be string, not None
:
def CleanUpFolder(dir):
do = dir
dir_with_original_files = dir
for root, dirs, files in os.walk(do):
for d in dirs:
for f in files:
print f.title()
if f.endswith('~'): #you don't want to process backups
continue
original_file = os.path.join(root, f)
with open(original_file, 'w') as orig_f, \
open(original_file, 'r') as orig_f2:
soup = BeautifulSoup(orig_f2.read())
for t in soup.find_all('td', class_='TEXT'):
t.string.wrap(soup.new_tag('h2'))
# This is where you create your new modified file.
orig_f.write(soup.prettify().encode(soup.original_encoding))
CleanUpFolder('C:\Users\FOLDER')
我在这里错过了什么?我不确定的主要是这条线如何
for root, dirs, files in os.walk(do):
在这种情况下被使用/理解了吗?
【问题讨论】:
-
您不需要递归调用,这就是
os.walk的用途。回到基础;只需运行for root, dirs, files in os.walk(do): print root, dirs, files看看会发生什么。 -
除非您在实际代码中转义路径,否则传递给函数的路径实际上是:
C:sersolder。确保转义路径'C:\\Users\\FOLDER'或使用原始字符串r'C:\Users\FOLDER'。此外,函数名称不应以大写字母开头,因为其他人看到它会认为它是class而不是function。 -
另外,FWIW 您的错误(“第 25 行的错误,在 CleanUpFolder”)显然与递归无关(“显然”对于花费几秒钟实际阅读错误消息的人来说,在最少)。
-
这与整洁无关;如果你
walk并在dirs上递归调用CleanUpFolder,则在深度n的目录中清理它2 ** n次! -
仍然是“真正的”错误:
soup.prettify().encode("some-encoding-here")不会完全按照您的意愿行事:它确实会将soup.prettify()的结果编码为您传递的任何编码,但是您的 html“内容类型”元数据中声明了错误的编码,参见 crummy.com/software/BeautifulSoup/bs4/doc/#output-encoding。你想要'soup.prettify("some-encoding-here"),然后不需要.encode()结果。
标签: python oop python-2.7 python-3.x recursion