繁体   English   中英

从 python 中的字典中获取最后一个 csv 文件

[英]Get last csv-file from dictionary in python

我目前正在编写一个脚本,该脚本可以从特定路径中的 csv 文件中生成数字。 csv 文件的编号如下:session-9995、session-9996 等,直到 session-9999。 所以我的脚本在正确的路径中搜索这些文件,加载数据和 plot 值与时间。 问题是我已经达到了 session-10000。 At some reason python thinks that this session is the first session instead of the last session, because the sessions will be searched as strings. 我的问题是:我该如何改变这一点,以便如果我要求运行最后一个 session,它需要正确的一个(所以 session-10000)? 加载数据的脚本部分是:

dic = {}
client_folders = glob.glob(MAIN_FOLDER + '*')
last_client_session = []
last_session = []
a = []
for client_folder in client_folders:
    save_results_to = client_folder + '/afbeeldingen'
    client = os.path.split(client_folder)[-1]
    if client not in CLIENTS_TO_PROCESS and CLIENTS_TO_PROCESS:
        continue
    last_client_session.append(glob.glob(client_folder + '/Sessies/*.csv')[-1]) 
    dic[client_folder] = last_client_session[-1]

所以“last_client_session”需要是 session-10000 而不是 session-9999。 任何人都可以帮助我吗?

我建议不要依赖 glob 的顺序,而是创建一个小例程来查找其中数字最高的文件名。 要使用的快速示例 function 可以是:

def get_last_file (names):
    numbers = [int(name.split('-')[1].split('.')[0]) for name in names]
    max_ix = numbers.index(max(numbers))
    return names[max_ix]

# Test the function
files = ['file-'+str(n) +'.csv' for n in range(1000, 10002)]
print(get_last_file(files))

然后可以将这样的东西用于您的last_client_session.append行:

files = glob.glob(client_folder + '/Sessies/*.csv')
last_client_session.append(get_last_file(files))

你可以测试这个脚本:

import os

current_dir = os.path.dirname(__file__)
files = [f for f in os.listdir(current_dir) if f.endswith(".csv")]
print(f"{files = }")
ids = [int(f.replace("session-", "").replace(".csv", "")) for f in files]
print(f"{ids = }")
paths = [os.path.join(current_dir, f) for f in [x for _, x in sorted(zip(ids, files))]]
print(f"{paths = }")
last_file = paths[-1]
print(f"{last_file = }")

Output:

/usr/bin/python3.9 /home/vince/Bureau/stackoverflow/test.py
files = ['session-9999.csv', 'session-10000.csv']
ids = [9999, 10000]
paths = ['/home/vince/Bureau/stackoverflow/session-9999.csv', '/home/vince/Bureau/stackoverflow/session-10000.csv']
last_file = '/home/vince/Bureau/stackoverflow/session-10000.csv'

它按 id 对所有文件进行排序,然后获取列表的最后一个文件。 你只需要通过它的完整路径打开它。

这是文件组织:

/home/vince/stackoverflow
    |test.py
    |session-9999.csv
    |session-10000.csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM