首页 > 解决方案 > 如何跳过或忽略python中的空文件?

问题描述

如何跳过/忽略空的 tdms 文件 (0KB) 进入我的最终 excel 文件?这是我使用的代码,但是当我打开 Excel 表时,我仍然发现它收集了空文件。

有人对此有解决方案吗?

source1 = r'D:FolderX'
location2 = 'c:\data\AM\Desktop\destination'

black_list = ['folder1', 'folder2'] 

for root, dirs, files in os.walk(source1):
    #Exclude the blacklist folders.
    dirs[:] = [d for d in dirs if d not in black_list]
    for file in files:
        if file.endswith(".tdms"):
            tdms_path = (os.path.join(root, file)) 
            file_size = os.path.getsize(tdms_path)
            
            if file_size == 0:
                 continue
        metadata = td.read_metadata(tdms_path)
        print(metadata)
        dfs.append(pd.DataFrame([metadata.properties.values()], columns=metadata.properties.keys()))

df = pd.concat(dfs)
df.to_excel(locatie2 + '\\' + 'final_sheet.xlsx')

标签: pythonexcelfile

解决方案


与 OP 的讨论已确认.tdms输出中只需要结尾的文件。代码的问题在于,如果文件名没有以.已被处理(并且在处理文件时始终设置变量,无论大小是零还是非零)。通过引入带有语句的块来修复该错误,以便任何非文件都不会触发任何进一步的处理。.tdmsmetadata = ...tdms_pathtdms_path.tdmselsecontinue.tdms

import os    # <=========  import added here

source1 = r'D:FolderX'
location2 = 'c:\data\AM\Desktop\destination'

black_list = ['folder1', 'folder2'] 

for root, dirs, files in os.walk(source1):
    #Exclude the blacklist folders.
    dirs[:] = [d for d in dirs if d not in black_list]
    for file in files:
        if file.endswith(".tdms"):
            tdms_path = (os.path.join(root, file)) 
            file_size = os.path.getsize(tdms_path)
            if file_size == 0:
                 continue
        else:                    # <=== skip if not a .tdms file
            continue             # <=== (otherwise uses tdms_path from earlier iteration)
        metadata = td.read_metadata(tdms_path)
        print(metadata)
        dfs.append(pd.DataFrame([metadata.properties.values()], columns=metadata.properties.keys()))

df = pd.concat(dfs)
df.to_excel(locatie2 + '\\' + 'final_sheet.xlsx')

关于这个错误是如何产生的,并且可以更容易地检测到。在循环的每次迭代中,变量tdms_path有时被赋值,有时未被赋值。当它没有被赋值时,使用的值可能会保留在早期的迭代中。这增加了更多的错误空间。如果该值在每次迭代中被显式初始化为None或类似,例如:

    for file in files:
        tdms_path = None  # <==== *this*
        if file.endswith(".tdms"):
            tdms_path = (os.path.join(root, file)) 
            # ... etc ...

然后当一个非.tdms文件被处理并执行到语句metadata = td.read_metadata(tdms_path)时(因为关于丢失的错误else: continue), 的值tdms_path将是None而不是早期迭代的值。调试起来会更加明显。


推荐阅读