使用os.walk()联接子目录

时间:2018-10-18 08:26:45

标签: python python-3.x

scripts/build1.js

我无法访问with open('images.txt', 'w') as text_file: for folderName, subfolders, f in os.walk(root_folder): for subfolder in subfolders: if subfolder == 'image_02': left_path = os.path.join(folderName, subfolder, 'data') left_list = [f for f in sorted(os.listdir(left_path)) if not f.startswith('.') and f.endswith('.png')] elif subfolder == 'image_03': right_path = os.path.join(folderName, subfolder, 'data') right_list = [f for f in sorted(os.listdir(right_path)) if not f.startswith('.') and f.endswith('.png')] if len(left_list) != len(right_list): print('ERROR: directory {} does not match with {}'.format(left_path, right_path)) continue for left_file, right_file in zip(left_list, right_list): text_file.write( os.path.join(left_path, left_file) + " " + os.path.join(right_path, right_file) + "\n") left_list来加入它们的路径,因为它们肯定超出了范围。
谁能说出如何用更好的代码结构来解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以在

之外初始化列表。
UPDATE user SET authentication_string=PASSWORD("newpass") WHERE User='root';

答案 1 :(得分:0)

    with open(dataset['destination'], 'w') as text_file:
        left_list = []
        right_list = []

        for folderName, subfolders, f in os.walk(root_folder):
            for subfolder in subfolders:
                if subfolder == 'image_02':
                    left_path = os.path.join(folderName, subfolder, 'data')
                    for f in sorted(os.listdir(left_path)):
                        if not f.startswith('.') and f.endswith('.png'):
                            left_list.append(f)
                elif subfolder == 'image_03':
                    right_path = os.path.join(folderName, subfolder, 'data')
                    for f in sorted(os.listdir(right_path)):
                        if not f.startswith('.') and f.endswith('.png'):
                            right_list.append(f)

        if len(left_list) != len(right_list):
            print('ERROR: directory {} does not match with {}'.format(left_path, right_path))
            continue

        for left_file, right_file in zip(left_list, right_list):
            text_file.write(
                os.path.join(left_path, left_file) + " " + os.path.join(right_path, right_file) + "\n")

这将是更好的方法!