我写了一个简单的脚本,它在一个文件夹上运行,并将在一个文件夹中的所有文件中循环执行一些处理(实际处理并不重要)。你知道吗
我有一个文件夹。此文件夹包含多个不同的文件夹。在这些文件夹中有数量可变的文件,我想在这些文件上运行我编写的脚本。我正在努力调整我的代码来做到这一点。你知道吗
所以以前,文件结构是:
Folder
Html1
Html2
Html3
...
现在是:
Folder
Folder1
Html1
Folder2
Html2
Html3
我仍然想在所有的HTMLs上运行代码。你知道吗
这是我的尝试,结果是
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):
在这种情况下是否有意义?你知道吗
在这里,我将您的函数分为两个独立的函数,并清除了多余的代码:
这已经解决了缩进问题,并且使测试函数和隔离将来的错误变得更容易。我还删除了
dirs
上的循环,因为这将在walk
内发生(这意味着您将跳过任何dir
中不包含任何子dirs
的所有files
)。你知道吗请注意,我已经将
original_file
的两个open
分开,这样您就不会在读取之前意外地覆盖它—不需要同时打开它进行读写。你知道吗我没有在这里安装
BeautifulSoup
,因此无法进一步测试,但这应该允许您将问题缩小到特定的文件。你知道吗相关问题 更多 >
编程相关推荐