Home > database >  Split specific line in text file to x, y variables in python
Split specific line in text file to x, y variables in python

Time:03-21

I have made a code in python that read text file (Test.text), the text file contains data like in below

10 20
15 90
22 89
12 33

I can read specific line by use this code

  particular_line = linecache.getline('Test.txt', 1)
  print(particular_line)

I tried to use code to split the text file to x, y value but it got all lines not the specific line that I need

with open('Test.txt') as f:
x,y = [], []
for l in f:
    row = l.split()
    x.append(row[0])
    y.append(row[1])
    

So how to get specific line and split it to two values x and y

CodePudding user response:

You might do

  particular_line = linecache.getline('Test.txt', 1)
  print(particular_line)
  x, y = particular_line.split()
  print(x)  # 10
  print(y)  # 20

.split() does give list with 2 elements, I used so called unpacking to get 1st element into variable x and 2nd into y.

CodePudding user response:

You are missing the readlines in your code

with open('Test.txt') as f:
x,y = [], []
for l in f.readlines():
    row = l.split()
    x.append(row[0])
    y.append(row[1])

CodePudding user response:

import pandas as pd

xy = pd.read_csv("Test.txt", sep=" ", header=None).rename(columns={0:"x", 1:"y"})

Now you can access to all x and y values with xy.x.values and xy.y.values. Note that I chose sep=" " as separator becose I suppose that your x and y are separated by a single space in you file.

CodePudding user response:

This is a rather condensed example:

with open("input.txt", "r") as f:
    data = f.read()

# Puts data into array line by line, then word by word
words = [y.split() for y in data.split("\n")]

# Gets first word (x)
x = [x[0] for x in words]
# Gets second word (y)
y = [x[1] for x in words]

Where [y.split() for y in data.split("\n")] gets each line by splitting at \n and splits the x and y values (.split()) by the space in-between them

CodePudding user response:

To get the specific line you can use this code

with open('Test.txt') as f:
    particular_line = f.readlines()[1]
    print(particular_line)

Notice the index inside [], it starts from 0 as same as most other languages. For example, if you want to get the first line, you'd change it to 0. By parsing it into two variables you can use

    x, y = particular_line.split()
    print(x)
    print(y)

So, put them together,

with open('Test.txt') as f:
    particular_line = f.readlines()[1]
    print(particular_line)
    x, y = particular_line.split()
    print(x)
    print(y)

You might also need it in a function format,

def get_particular_line_to_x_y(filename, line_number):
    with open(filename) as f:
        particular_line = f.readlines()[line_number]
        return particular_line.split()

if __name__ == '__main__':
    x, y = get_particular_line_to_x_y('Test.txt', 0)
    print(x)
    print(y)
  • Related