python从文件中读取数据
问题描述:
我有一个非常简单的问题:哪种方法可以用Python从txt文件中读取不同的条目?python从文件中读取数据
想我也一个文本文件,如:
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")
答
我会抬头看string.split()方法
例如,你可以使用
for line in file.readlines():
data = dict(zip(("id", "t0", "score", "date", "time"), line.split(" ")))
instructions()
答
根据你想用数据做什么,pandas可能是一些寻找到:
import pandas as pd
with open(file_name) as infile:
df = pd.read_fwf(infile, header=None, parse_dates=[[3, 4]],
date_parser=lambda x: pd.to_datetime(x, format='%d/%m/%Y %H:%M:%S'))
双列表[[3, 4]]
连同date_parser
参数将作为单个数据时间对象读取第三个和第四个(索引为0的)列。然后,您可以访问该列的各个部分与
>>> df['3_4'].dt.hour
0 13
1 13
2 15
3 18
4 15
5 5
dtype: int64
(如果你不喜欢 '3_4' 键,使用parse_dates
上面的参数如下:
parse_dates={'timestamp': [3, 4]}
)
read_fwf
用于读取数据似乎遵守的固定宽度列。另外,还有一些功能,如read_csv
,read_table
和lot more。
(这个答案是非常的this SO answer重复,而是因为在这里这个问题就比较一般了,我已经把这个这里另一种答案,而不是作为一个评论。)的[Python的最快方法
可能重复阅读一个大的文本文件(几GB)](http://stackoverflow.com/questions/14944183/python-fastest-way-to-read-a-large-text-file-several-gb) – user3636636
你想取决于列的字符串列表或类型列表? – FunkySayu
你可以看看Numpy [loadtxt](http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html) – Mel