首页 > 解决方案 > 使用 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)

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

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

我在做什么阻止创建所有三个文件?

标签: pythonexport-to-csv

解决方案


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

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


推荐阅读