我尝试对文件中每个var
的数值求平均值。它在var_values=1.0
上工作正常,但在var_values=5.0,10.0
上不工作。我给出当前输出。预期输出应为var_values=5.0,10.0
的数值,因为相应文件夹中的每个文件都具有非零值。
import os
import csv
NFILES = 501
Folder_name = '4_1012_nodes_var_1_K_1e3_Cb_1e-3_D_1e-10'
K = 1e3
Cb = 1e-3
DiffCoeff = 1e-10
mean_radii = 50.0
var_values = [1.0, 5.0, 10.0]
Distribution = 'ND'
for var in var_values:
numeric_values = [] # Reset the list for each var iteration
file_count = 0 # Counter for the number of files processed
for i in range(1, NFILES):
folder_path = rf"D:\Users\debanikb\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\{Folder_name}\{i}\Time_{mean_radii}_{var}{Distribution}_{K}_{Cb}_{DiffCoeff}.csv"
if os.path.isfile(folder_path):
with open(folder_path, 'r') as file:
reader = csv.reader(file)
row_values = []
for row in reader:
for value in row:
try:
numeric_value = float(value)
row_values.append(numeric_value)
except ValueError:
pass
if row_values:
numeric_values.extend(row_values)
file_count += 1
if file_count > 0:
average = sum(numeric_values) / len(numeric_values)
print(f"Average of numeric values for var={var}:", average)
print(f"Number of files averaged for var={var}:", file_count)
else:
print(f"No numeric values found for var={var}.")
字符串
文件的数据格式如下所示
的数据
当前输出为
Average of numeric values for var=1.0: 1.4373770078023274
Number of files averaged for var=1.0: 34
No numeric values found for var=5.0.
No numeric values found for var=10.0.
型
1条答案
按热度按时间b4lqfgs41#
由于文件内容非常简单,真实的不需要CSV模块。
就这样做:
字符串
此时,字典 results 和 file_count 将包含继续操作所需的所有信息
型