Skip to main content
 首页 » 编程设计

python从文件中读取数据

2024年10月24日12txw1958

我有一个非常简单的问题:使用 Python 从 txt 文件中读取不同条目的最有效方法是什么?

假设我有一个像这样的文本文件:

42017     360940084.621356  21.00  09/06/2015  13:08:04 
42017     360941465.680841  29.00  09/06/2015  13:31:05 
42017     360948446.517761  16.00  09/06/2015  15:27:26 
42049     361133954.539315  31.00  11/06/2015  18:59:14 
42062     361208584.222483  10.00  12/06/2015  15:43:04 
42068     361256740.238150  19.00  13/06/2015  05:05:40 

在 C 中我会这样做:

while(fscanf(file_name, "%d %lf %f %d/%d/%d %d:%d:%d", &id, &t0, &score, &day, &month, &year, &hour, &minute, &second) != EOF){...some instruction...} 

在 Python 中执行此类操作的最佳方法是什么?为了将每个值存储到不同的变量中(因为我必须在整个代码中使用这些变量)。

提前致谢!

请您参考如下方法:

我觉得muddyfish的回答不错,这里是另一种方式(可能更轻一点)

import time 
with open(file) as f: 
    for line in f: 
        identifier, t0, score, date, hour = line.split() 
 
        # You can also get a time_struct from the time 
        timer = time.strptime(date + hour, "%d/%m/%Y%H:%M:%S")