[英]How to access files in folder with same string in file name in python?
我正在嘗試使用 python 來查看目錄文件夾並匹配文件名中具有相同字符串的文件。 此文件夾中的每個感興趣的文件都是一個“.csv”文件,其中包含一個值列, Value_Blue
用於藍色文件, Value_Red
用於紅色文件。 The files in this folder go: Blue_111.csv, Blue_124.csv, Blue_145.csv, Blue_165.csv, Blue_176.csv... and then: Red_111.csv, Red_124.csv, Red_145.csv, Red_165.csv, Red_176. csv...等等。 如圖所示,與這些文件中的每一個相關聯的數字不是等間隔順序的 go,但這與此處無關。 對於大多數藍色文件,有一個匹配的紅色文件,文件名附加了相同的編號擴展名。 因此,有些藍色文件沒有對應的紅色文件。
我要做的是遍歷目錄文件夾中的所有藍色文件,將它們作為數據幀打開,然后找到匹配的紅色文件,將該文件作為 Z6A8064B5DF4794555500553C47C55057DZ 打開,然后將這兩個數據幀中的Value
列相乘,然后將新的 dataframe 發送到新的 csv 文件名包含相同的擴展名。
例如,如果在循環中它以 Blue_111.csv 開頭,那么我希望它找到 Red_111.csv。 我希望將這兩個.csv 文件作為數據框打開,並且Value
列成倍增加。 I then want to send this newly calculated dataframe to a new.csv called `Green_111.csv, and then keep going in the loop onto Blue_124.csv, etc.
這是示例我的目標的偽代碼:
folder = Path/to/Directory/Folder
for f in folder that is a .csv with "Blue" in filename:
blue_df = pd.read_csv(f)
red = matching Red file
red_df = pd.read_csv(red)
green_df = blue_df.join(red_df)
green_df = green_df['Value_Blue'] * green_df['Value_Red']
green_df.to_csv(Path/to/Directory/Folder/Green_*matching_number*.csv)
如何匹配文件,然后在文件名中創建具有相同匹配擴展名的計算 output 文件?
使用glob.glob()
匹配所有匹配通配符模式的文件名。 然后您可以使用.replace()
將Blue
替換為Red
和Green
以創建其他文件名。
import glob, os
folder = 'Path/to/Directory/Folder'
for blue in glob.glob(os.path.join(folder, "Blue_*.csv")):
blue_df = pd.read_csv(blue)
red = blue.replace("Blue_", "Red_")
green = blue.replace("Blue_", "Green_")
red_df = pd.read_csv(red)
green_df = blue_df.join(red_df)
green_df = green_df['Value_Blue'] * green_df['Value_Red']
green_df.to_csv(green)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.