Home>

I'm looping through the csv files in a folder with the for in syntax.
Every time the loop is repeated, the file is overwritten and the file becomes
You can only get one.

Files that meet the conditions with the if syntax are placed in the specified folder.
I want to save each file that does not meet the conditions with else to the specified folder.

Error message
Corresponding source code

if len (card_and_measure)>= 3:
print ("success")
data.to_csv ('TA2.csv', index = False, encoding ='SHIFT_JIS')
else: else:
print ("impossible")

import pandas as pd
import glob
import os
for file in glob.glob ('TA * .csv'): Search for csv files in #file and read them all
    basename = os.path.basename (file)
    name = os.path.splitext (basename) [0]
    data = pd.read_csv (file,
       names = ["2θ", "Intensity"],
       encoding = "SHIFT_JIS")

    mycsv = pd.read_csv ('TA.csv', names = ["2θ", "Intensity"], encoding = "SHIFT_JIS") # Added because there is no header
    card = mycsv.sort_values ​​(by = "Intensity", ascending = False) Sort #Intensity lines in descending order by ascending = False
    measure = data.sort_values ​​(by = "Intensity", ascending = False) .head (50) # Extract only 100 from the top in descending order
    measure_x = measure.iloc [:, 0]
    card_x = card.iloc [:, 0]
    card_measure_and = set (card_x)&set (measure_x)
    card_and_measure = list (card_measure_and)
    if len (card_and_measure)>= 3:
        print ("success")
        data.to_csv ('TA2.csv', index = False, encoding ='SHIFT_JIS')
    else: else:
        print ("impossible")
What I tried

I made an empty list, but I couldn't understand it and gave up.

Supplementary information (FW/tool version, etc.)

python 3.7, spyder

  • Answer # 1

    As belowbasenameIt is a good idea to save it with.
    By the way, in the following code, the read source file remains in the original location.

    import glob
    import os
    import pandas as pd
    for file in glob.glob ('TA * .csv'):
        basename = os.path.basename (file)
        df = pd.read_csv (file)
        if condition is met:
            df.to_csv (os.path.join ('/ hoge/ok /', basename))
        else: else:
            df.to_csv (os.path.join ('/ hoge/ng /', basename))

  • Answer # 2

    Because the CSV file name of the output destination is fixed to TA2.csv in data.to_csv
    The same file has been overwritten.

    Since the CSV file is stored in the variable "file" for each loop in the for statement

    data.to_csv ('TA2.csv', index = False, encoding ='SHIFT_JIS')


    data.to_csv (file, index = False, encoding ='SHIFT_JIS')


    How about fixing it to?

Related articles