将变量分配给文件夹中的所有文件以供访问

发布于 2025-01-13 01:42:12 字数 506 浏览 2 评论 0原文

我有一个包含“.pkl”文件的文件夹。我想访问这些多个文件中的数据来绘制结果。

当我尝试使用 for 循环执行此操作时出现错误。我的所有 .pkl 文件的文件名中都包含编号,例如 meta_room_1_reg.pkl、meta_room_2_reg.pkl 等。所以我想为每个变量分配一个变量。

目前,我正在使用 if 和 find() 语句来执行此操作。但这并不理想。

我的代码在这里:

all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
for i, curr_file in enumerate(all_files):
    with open(curr_file, 'rb') as f:
        mydata = pickle.load(f)
        if curr_file.find('1'):
            myfile = mydata

请指导。

I have a folder that contains'.pkl' files. I want to access the data inside those multiple files to plot my results.

I am getting an error when I try to do it with a for loop. All my .pkl files contain numbering in their filename like meta_room_1_reg.pkl, meta_room_2_reg.pkl and so on. So I want to assign a single variable to each and every one.

Currently, I am doing that with an if and find() statement. But that is not ideal.

My code is here:

all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
for i, curr_file in enumerate(all_files):
    with open(curr_file, 'rb') as f:
        mydata = pickle.load(f)
        if curr_file.find('1'):
            myfile = mydata

Please guide.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2025-01-20 01:42:12

我假设您想要收集所有数据以列出或类似的东西,对吧?

使用 .append 方法,而不仅仅是赋值。

    myfiles = []
    all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
    for i, curr_file in enumerate(all_files):
        with open(curr_file, 'rb') as f:
            mydata = pickle.load(f)
            if curr_file.find('1'):
                myfiles.append(mydata)

I'm assuming that you want to collect all data to list or something like that, right?

Use the .append method, instead of just an assignment.

    myfiles = []
    all_files = glob.glob('D:/Master Thesis/MCDM Combined code/results/*.pkl')
    for i, curr_file in enumerate(all_files):
        with open(curr_file, 'rb') as f:
            mydata = pickle.load(f)
            if curr_file.find('1'):
                myfiles.append(mydata)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文