有2个文件夹分别为文件夹1和文件夹2,文件夹1包含以年-月-日格式时间为命名的txt文件,每个txt内格式为数字文本加逗号加数字文本,文件夹2包含以年-月-日格式时间命名的子文件夹,子文件夹包含以数字文本命名的csv文件。要求输入一个日期,找出文件夹1这个日期的txt文件和文件夹2的子文件夹这个日期下的文件,找到以这个日期下与txt文件中的数字文本同名的文件夹2子文件中的csv文件,将这些csv文件进行以第一列重复值进行分组,再找到以第三列重复值进行分组后其他列进行求和,并按每个csv进行画图,x轴为第一列数据,y轴为对应的求和数据并保存
时间: 2023-06-10 13:04:45 浏览: 28
您好!感谢使用 ChitGPT 进行交流!
根据您的要求,您可以尝试以下 Python 代码来实现您的需求:
```python
import os
import glob
import pandas as pd
import matplotlib.pyplot as plt
folder1 = '文件夹1'
folder2 = '文件夹2'
# 输入要查找的日期,格式为年-月-日
date = input('请输入日期(格式为年-月-日):')
# 在文件夹1中查找符合日期命名的txt文件
txt_files = glob.glob(os.path.join(folder1, f'{date}.txt'))
# 在文件夹2中查找符合日期命名的子文件夹并读取其中的csv文件
csv_files = []
sub_folders = glob.glob(os.path.join(folder2, f'{date}/*'))
for sub_folder in sub_folders:
csv_files += glob.glob(os.path.join(sub_folder, '*.csv'))
# 将符合条件的csv文件按第一列进行分组,并按第三列进行求和
result = {}
for csv_file in csv_files:
df = pd.read_csv(csv_file)
group = df.groupby(df.columns[0])
sum_df = group.agg({df.columns[2]: 'sum'}).reset_index()
result[csv_file] = sum_df
# 画图并保存
plt.figure(figsize=(10, 5))
plt.plot(sum_df.iloc[:,0], sum_df.iloc[:,1])
plt.xlabel(df.columns[0])
plt.ylabel(df.columns[2])
plt.title(os.path.basename(csv_file))
plt.savefig(f'{os.path.splitext(csv_file)[0]}.png')
plt.close()
# 输出结果
if len(txt_files) == 0:
print('未找到符合条件的txt文件!')
else:
print('符合条件的txt文件为:')
for txt_file in txt_files:
print(txt_file)
if len(csv_files) == 0:
print('未找到符合条件的csv文件!')
else:
print('符合条件的csv文件为:')
for csv_file in csv_files:
print(csv_file)
print(result[csv_file])
```
请注意,此代码仅供参考,具体实现还需要根据您的具体情况进行调整。如果您有任何问题或需求,请随时告诉我,我会尽力帮助您!