简体   繁体   English

从.txt文件中读取第N行(Python)

[英]Reading every Nth line from a .txt file (Python)

I am making a program that reads time values and readings from a .txt file and plots them on a web-page with matplotlib. 我正在编写一个程序,该程序从.txt文件读取时间值和读数,并使用matplotlib将其绘制在网页上。 In my case there are lots of values, and the plot can look very confusing, and with thousands of data points it can also be sluggish. 在我的情况下,有很多值,并且该图看起来非常混乱,并且由于有成千上万个数据点,它也可能很慢。

I am currently reading the .txt lines with this code to put the values into plottable lists: 我目前正在使用此代码读取.txt行,以将值放入绘图表列表中:

with open('C:/Email/file.txt') as f:   


    lines = f.readlines()



    dates = [str(line.split(';')[0]) for line in lines]
    y = [float(line.split(';')[1]) for line in lines]
    z = [float(line.split()[2]) for line in lines]

The .txt file content looks like this: .txt文件的内容如下所示:

30.05.18_12:27:17;  13.0;  -0.0
30.05.18_12:27:18;  14.0;  -0.0
30.05.18_12:27:19;  15.0;  -0.0
30.05.18_12:27:20;  16.0;  -0.0

So, is there any way to read and plot every Nth (for example every 30. would be ideal) timestamp and value? 那么,是否有任何方法可以读取和绘制每N分之一的时间戳和值(例如,每30个为佳)。

I've been researching different ways but they seem confusing. 我一直在研究不同的方法,但它们似乎令人困惑。

One solution that I was thinking about is to make a counter that counts the amount of read lines, then when the counter is 30, skip 30 the next lines and read and plot the data in line 31. I have no idea how to do this, since I am relatively new to Python. 我正在考虑的一种解决方案是创建一个计数器,用于对读取的行数进行计数,然后当计数器为30时,跳过30行,然后在第31行读取并绘制数据。我不知道该怎么做,因为我刚接触Python。

Help would be appreciated. 帮助将不胜感激。

Just in case, the whole code here: 以防万一,整个代码在这里:

from flask import Flask
import numpy as np
import matplotlib.pyplot as plt, mpld3
from datetime import datetime

app = Flask(__name__)



@app.route("/")
def hello():

    with open('C:/Email/file.txt') as f:   


        lines = f.readlines()



        dates = [str(line.split(';')[0]) for line in lines]
        y = [float(line.split(';')[1]) for line in lines]
        z = [float(line.split()[2]) for line in lines]


        date = [datetime.strptime(x,'%d.%m.%y_%H:%M:%S') for x in dates]
        plt.figure(figsize=(10,5))
        plt.title('Temperature', fontsize=15)
        plt.ylabel('Temperature' + u'\u2103', fontsize=15)

        plt.plot_date(date, y, 'r-', label='quadratic')
        plt.ylim([10,35])

        # Print as HTML
        return mpld3.show()

if __name__ == "__main__":
    app.run()

EDIT: HUGE THANKS TO MR. 编辑:非常感谢先生。 F-ROCHE F-ROCHE

Got it working with the following code: 使用以下代码进行处理:

@app.route("/")
def hello():

    with open('C:/Email/file.txt') as f:   

        # Counts lines in text (Use later to delete lines every X readings)
        # lines = f.readlines()
        cpt = 0
        all_lines = []
        for line in f:
            cpt += 1
            if cpt == 30:
                all_lines.append(line)
                cpt = 0
        dates = [str(line.split(';')[0]) for line in all_lines]
        date = [datetime.strptime(x,'%d.%m.%y_%H:%M:%S') for x in dates]
        y = [float(line.split(';')[1]) for line in all_lines]
        z = [float(line.split()[2]) for line in all_lines]

        plt.figure(figsize=(10,5))
        plt.title('Temperature', fontsize=15)
        plt.ylabel('Temperature' + u'\u2103', fontsize=15)


        plt.plot_date(date, y, 'r-', label='quadratic')
        plt.ylim([10,35])

        # Print as HTML
        return mpld3.show()

Something like that will only display every 30 lines: 诸如此类的内容将仅每30行显示一次:

with open('C:/Email/file.txt') as f:
    cpt = 0
    for line in f:
        cpt += 1
        if cpt == 30:
            print(line)
            cpt = 0

you can put line variable in a list like this: 您可以将line变量放在这样的列表中:

all_lines = []
...
all_lines.append(line)

EDIT: or even better with one line of code: 编辑:甚至用一行代码更好:

with open('C:/Email/file.txt') as f:
    all_lines = [v for i, v in enumerate(f, start=1) if i % 30 == 0]

Then you can apply that to dates , y and z instead. 然后,您可以将其应用于datesyz

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

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