简体   繁体   中英

Python - plot from txt file, skipping lines

I have a problem with my script. I have (blabla.)txt file, for example:

blablaba bla
dsadsadsa
dsadsadsa
50 2323
60 2839
70 9832
80 0000
.....
....
...

and script I wrote:

import numpy as np
import matplotlib.pyplot as plt

with open("blabla.txt") as f:
    for line in xrange(3):
        next(f)
    for line in f:

      data = f.read()

      data = data.split('\n')

      x = [row.split()[0] for row in data]
      y = [row.split()[1] for row in data]

      index = [i for i,val in enumerate(x)]

      fig = plt.figure()
      ax1 = fig.add_subplot(111)
      ax1.set_title("graph")    
      ax1.set_xlabel('time')
      ax1.set_ylabel('distance')
      ax1.set_xticklabels(x)
      ax1.plot(index ,y, c='r', label='distance1')
      leg = ax1.legend()
      plt.locator_params(nbins=len(index)-1)
      plt.show()

The first question is: Is it true (syntax in the script) when I want to skip (because of the graph) the first three lines in the txt file?

The second: After runscript it says:

data = f.read()
ValueError: Mixing iteration and read methods would lose data.

What is the problem, its because of size? (txt file has about 600 000 lines)

Thanks for all the help....Funstorm60

You can use:

with open("<fname>.txt", 'r') as datafile:
    __data = datafile.readlines()[3:]

data = [[float(value) for value in line.split()] for line in __data]

This will give you a 2D array of your data - although it doesn't include the index information that you've included in your question.

EDIT: Sorry I missed the call to .split()

EDIT: As an example

1 2 3 4
2 3 4 5
6 5 4 3

will give the output:

[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0], [6.0, 5.0, 4.0, 3.0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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