【问题标题】:I need to read in a file and split it into different columns in Python我需要读入一个文件并将其拆分为 Python 中的不同列
【发布时间】:2014-04-08 21:07:08
【问题描述】:

我没有太多使用 Python 的经验,我正在尝试读取日志文件。到目前为止,我能够读取文件并打印出来。

infile = open("C:\file.log", "r")
lines = infile.readlines()
print lines
print len(lines)
infile.close()

文件包含双精度值和时间戳,例如:

08 Apr 2014 00:00:31, 22.198, 5.444, 67.901
08 Apr 2014 00:00:31, 33.198, 6.444, 54.901
08 Apr 2014 00:00:31, 44.198, 5.444, 84.901
08 Apr 2014 00:00:31, 55.198, 8.444, 94.901

这些值中的每一个都是不同的测量值,即。第一个数字是时间戳,第二个是 CPU 使用率等。我如何读取这些并将每列存储到不同的数组中??

【问题讨论】:

  • 为什么不创建一个字典

标签: python arrays file timestamp


【解决方案1】:
r = csv.reader(open(filename))
dates = []
times = []
cpus = []
usages = []
for d, t, v1, v2 in r:
    dates.append(d)
    times.append(t)
    cpus.append(float(v1)
    usages.append(v2)

希望这会有所帮助。

【讨论】:

  • 谢谢,这是很大的帮助! :)
【解决方案2】:

这是我阅读表格的首选方式。它以一个返回值结束,写起来很短。

#create a list of keys for each data entry
label_list = ["timestamp", "cpu_usage", "foo", "bar"]
# make a container to hold the entries
data = []
# using with/as is a safer way to open files
with open("C:\file.log", "r") as file:
    for line in file:
        # split the element
        value_list = line.split(", ")
        # create a dictionary for each entry, with label_list as keys
        data.append({})
        for value, label in zip(value_list , label_list):
            data[-1][label] = value
# whenever you want a group of items you can do this. ex) cpu_usage
print [d["cpu_usage"] for d in data]

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多