Python 个脚本在处理大量 CSV 文件和绘制图形时得到 "killed"

Python scripts gets "killed" while processing a large amount of CSV files and plotting figures

我有一个 python 脚本,它从 csv 文件的矢量位置和方向获取数据,然后使用 Matplotlib 的 quiver 方法生成绘图。使用 Pandas 数据框提取 csv 文件坐标和方向的列,然后使用 Matplotlib 中的 quiver 方法绘制。它适用于少量文件,但当我尝试处理超过 1000 个文件时,它会被“杀死”。任何有关如何解决此问题的想法都将受到高度赞赏。

# Import libraries
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

directory = './'     

for filename in os.listdir(directory):

    if filename.endswith(".csv"):

        print(os.path.join('./', filename))

        df = pd.read_csv(os.path.join(directory, filename))

        # import column of CSV file with x_pos info
        x_pos = df['x'].tolist()
        y_pos = df['y'].tolist()
        x_direct = df['x_dir'].tolist()
        y_direct = df['y_dir'].tolist()
        scale = df['scalar'].tolist()

        # Creating plot
        fig, ax = plt.subplots(figsize = (10, 10))
        ax.quiver(x_pos, y_pos, x_direct, y_direct, angles='xy', scale_units='xy', scale=1)

        plt.savefig(os.path.splitext(os.path.join(directory, filename))[0] + '.png')

        continue
    else:
        continue

保存后关闭图很重要:

for filename in os.listdir(directory):
    if filename.endswith(".csv"):
        ...

        fig, ax = plt.subplots(...)
        ax.quiver(...)

        plt.savefig(...)

        plt.close(fig)  # HERE: close figure

解析目录的提示:

import pathlib

directory = '.'

for filename in pathlib.Path(directory).glob('*.csv'):
    print(filename)
    df = pd.read_csv(filename)
    ...
    plt.savefig(filename.parent / f"{filename.stem}.png")