导出同一文件夹下多个 csv 文件的特定行,并制作一个新的 CSV 文件作为连接结果[关闭]

问题描述 投票:0回答:1
import csv
import glob
import pandas as pd
path = r'D:\Clouds\OneDrive\Desktop\python_tamrin_2'
all_files = glob.glob(path + "/*.csv")
print(all_files)
li=[]
for file in all_files:
    with open(all_files, 'r') as read_obj:
        csv_reader = csv.reader(read_obj)
        with open ('new_nemes_3.csv','w', newline='') as new_file:
            csv_writer=csv.writer(new_file)
            for row in csv_reader:
                if row[15] == 'INTERNAL_SOHO_DS_MISSING_NEIGHBOUR':
                    final =csv_writer.writerow(row[:35])
                    li.append(final)
            f= pd.concat(li,index_col=None,header=0)
            f.to_csv('final.csv',index=False,encoding='utf-8')
python export-to-csv glob
1个回答
0
投票

您可以使用 pandas 读取和处理 CSV 文件。然后遍历每个 CSV 文件,读入数据框,然后根据指定条件过滤行。它读取指定路径中的每个 CSV 文件,根据给定条件过滤行

看看是否可行,如果有任何问题,请告诉我:

import glob
import pandas as pd

path = r'D:\Clouds\OneDrive\Desktop\python_tamrin_2'
all_files = glob.glob(path + "/*.csv")

li = []

for file in all_files:
    df = pd.read_csv(file)

    filtered_rows = df[df.iloc[:, 15] == 'INTERNAL_SOHO_DS_MISSING_NEIGHBOUR']

    filtered_rows = filtered_rows.iloc[:, :35]

    li.append(filtered_rows)

result = pd.concat(li, axis=0, ignore_index=True)

result.to_csv('final.csv', index=False, encoding='utf-8')
© www.soinside.com 2019 - 2024. All rights reserved.