使用to_csv循环仅打印最后一个文件Python

问题描述

我正在尝试从一个文件夹中加载多个csv文件,使用一个函数来计算每个文件的缺失值,然后保存包含输出的新csv文件。当我编辑脚本以打印输出时,我得到了预期的结果。但是,循环只会将最后一个文件保存到目录中。我正在使用的代码是:

from pathlib import Path
import pandas as pd
import os
import glob

files = glob("C:/Users/61437/Desktop/test_folder/*.csv") # get all csv's from folder

n = 0

for file in files:
    print(file)
    df = pd.read_csv(file,index_col = False)
    d = calc_missing_prices(df) # calc_missing_prices is a user defined function
    print(d)
    d.to_csv(r'C:\Users\61437\Desktop\test_folder\derived_files\derived_{}.csv'.format(n+1),index = False)
@H_404_4@

print()命令返回预期的输出,对于我的数据是:

C:/Users/61437/Desktop/test_folder\file1.csv
   V_150  V_200  V_300  V_375  V_500  V_750  V_1000
0   3.00   2.75   4.50   6.03   8.35  12.07   15.00
1   2.32   3.09   4.63   5.00   9.75  12.50   12.25
2   1.85   2.47   3.70   4.62   6.17   9.25   12.33
3   1.75   2.00   4.06   6.50   6.78  10.16   15.20
C:/Users/61437/Desktop/test_folder\file2.csv
   V_300  V_375  V_500  V_750  V_1000
0   4.00   4.50   6.06   9.08   11.00
1   3.77   5.00   6.50   8.50   12.56
2   3.00   3.66   4.88   7.31    9.50
C:/Users/61437/Desktop/test_folder\file3.csv
   V_500  V_750  V_1000
0   5.50   8.25   11.00
1   6.50   8.50   12.17
2   4.75   7.12    9.50
@H_404_4@

但是,唯一保存的csv文件是'derived_1.csv',其中包含file3.csv的输出

我该怎么做才能阻止创建所有三个文件

解决方法

您没有在循环内递增n。您的数据将存储在文件derived_1.csv中,该文件在每次迭代时都会被覆盖。 for循环完成执行后,将仅保存最后一个csv。

n += 1循环中包含行for,以便在每次迭代时将其递增1。