adplus-dvertising

Extract data from .txt file

Asked 3 months ago
Viewed 9 times

I need to extract values of t,x,y from a .txt file. They are 3 columns next to each other, so first column is "t" , second is "x" and third is "y". I will add a picture. I have to write a code that will plot a graph with these values and I'm not sure how. Thank you.Extract data from .txt file

asked 3 months ago

Correct Answer

Not sure which graph you want to create but I can guide you how can you extract data from txt file and to create a graph.

To extract data from txt you can use this it will read every line from txt and convert it to lists using split method using empty space.

with open('your_file.txt', 'r') as datafile:
plotting = csv.reader(datafile, delimiter=' ')

Complete example for extraction and plotting:

import matplotlib.pyplot as plt
import csv
X = []
Y = [] 

with open('your_file.txt', 'r') as datafile:
    plotting = csv.reader(datafile, delimiter=' ')     
for ROWS in plotting:
    X.append(float(ROWS[0]))
    Y.append(float(ROWS[1]))
    T.append(float(ROWS[2])) 
plt.plot(X, Y)
plt.title('Line Graph using CSV')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
answered 3 months ago