简体   繁体   English

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

[英]Loop using to_csv only printing last file (Python)

I am trying to load a number of csv files from a folder, use a function that calculates missing values on each file, then saves new csv files containing the output.我正在尝试从文件夹中加载多个 csv 文件,使用计算每个文件缺失值的函数,然后保存包含输出的新 csv 文件。 When I edit the script to print the output, I get the expected result.当我编辑脚本以打印输出时,我得到了预期的结果。 However, the loop only ever saves the last file to the directory.但是,循环只会将最后一个文件保存到目录中。 The code I am using is:我正在使用的代码是:

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)

The print() command returns the expected output, which for my data is: 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

However the only saved csv file is 'derived_1.csv' which contains the output from file3.csv但是,唯一保存的 csv 文件是“衍生_1.csv”,其中包含 file3.csv 的输出

What am I doing that is preventing all three files from being created?我在做什么阻止创建所有三个文件?

You are not incrementing n inside the loop.您没有在循环内增加n Your data gets stored in the file derived_1.csv , which is overwritten on every iteration.您的数据存储在文件derived_1.csv ,每次迭代都会覆盖该文件。 Once the for loop finishes executing, only the last csv will be saved. for循环执行完毕后,将只保存最后一个 csv。

Include the line n += 1 inside the for loop to increment it by 1 on every iteration.for循环中包含行n += 1以在每次迭代时将其增加 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM