python - 如何跳过或忽略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')
解决方案
与 OP 的讨论已确认.tdms
输出中只需要结尾的文件。代码的问题在于,如果文件名没有以.已被处理(并且在处理文件时始终设置变量,无论大小是零还是非零)。通过引入带有语句的块来修复该错误,以便任何非文件都不会触发任何进一步的处理。.tdms
metadata = ...
tdms_path
tdms_path
.tdms
else
continue
.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
而不是早期迭代的值。调试起来会更加明显。
推荐阅读
- node.js - 命令在终端中工作,但不适用于 node.js
- django - Django表单初始值未显示
- sql-server - SQL VIEW 执行超时已过期
- postgresql - CTE 和 DML 语句的 PG 意外行为
- php - 为什么我得到数组到字符串的转换错误?
- sharepoint - Sharepoint 2013 Wiki 历史页面始终显示添加的第一个单词
- python - Python-Mysql插入查询
- html - 无法对齐连续 3 个元素。一个应该在左边,其余的应该居中
- amazon-s3 - Kafka S3 源连接器
- python - 我的 on_message 功能不再起作用