在Python中使程序递归地调用自己

2024-10-05 14:30:29 发布

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

我写了一个简单的脚本,它在一个文件夹上运行,并将在一个文件夹中的所有文件中循环执行一些处理(实际处理并不重要)。你知道吗

我有一个文件夹。此文件夹包含多个不同的文件夹。在这些文件夹中有数量可变的文件,我想在这些文件上运行我编写的脚本。我正在努力调整我的代码来做到这一点。你知道吗

所以以前,文件结构是:

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):

在这种情况下是否有意义?你知道吗


Tags: 文件in文件夹fordirrootfilesdo
1条回答
网友
1楼 · 发布于 2024-10-05 14:30:29

在这里,我将您的函数分为两个独立的函数,并清除了多余的代码:

def clean_up_folder(dir):
    """Run the clean up process on dir, recursively."""
    for root, dirs, files in os.walk(dir):
        for f in files:
            print f.title()
            if not f.endswith('~'): #you don't want to process backups
                clean_up_file(os.path.join(root, f))

这已经解决了缩进问题,并且使测试函数和隔离将来的错误变得更容易。我还删除了dirs上的循环,因为这将在walk内发生(这意味着您将跳过任何dir中不包含任何子dirs的所有files)。你知道吗

def clean_up_file(original_file):
    """Clean up the original_file."""      
    with open(original_file) as orig_f2:
        soup = BeautifulSoup(orig_f2.read())
    for t in soup.find_all('td', class_='TEXT'):
        t.string.wrap(soup.new_tag('h2'))
    with open(original_file, 'w') as orig_f:
        # This is where you create your new modified file.
        orig_f.write(soup.prettify().encode(soup.original_encoding))

请注意,我已经将original_file的两个open分开,这样您就不会在读取之前意外地覆盖它—不需要同时打开它进行读写。你知道吗

我没有在这里安装BeautifulSoup,因此无法进一步测试,但这应该允许您将问题缩小到特定的文件。你知道吗

相关问题 更多 >