Henry
Henry

Reputation: 67

Grabbing just the content of a line

I have a simple question: I want to just grab the content of a line from a file x. My file x looks like this:

PointXY
[387.93852, 200.0]
PointXY
[200.0, 387.93852]
PointXY
[200.0, 387.93852]
PointXY
[200.0, 353.20889]
PointXY
[387.93852, 200.0]
PointXY
[200.0, 387.93852]
PointXY
[200.0, 300.0]

My script in Python looks like this:

h = open("x.gcode", "r")
searchlines = h.readlines()
file = ""

for i, line in enumerate(searchlines):
    if "PointXY" in line:
        P = searchlines[i+1]
        print(P)

I want P to just be [200.0, 100.0] (for instance). It now gives me '[200.0, 100.0]\n'. How can I adjust this in the line "P = searchlines[i+1]"?

Upvotes: 0

Views: 49

Answers (3)

Milor123
Milor123

Reputation: 555

if you want delete '\n' use this

after read data

data = f.readlines()

data = map(str.strip, data)

but isn't necessary for the other you could use this:

import ast
listdata = []
with open('lel.txt') as f:
    data = f.readlines()
    for x in data:
        try:
            if isinstance(ast.literal_eval(x), list):
                listdata.append(eval(x))
        except:
            pass

then for get data of list:

print listdata
>>>[[387.93852, 200.0], [200.0, 387.93852], [200.0, 387.93852], [200.0, 353.20889], [387.93852, 200.0], [200.0, 387.93852], [200.0, 300.0]]
print listdata[0]
>>>[387.93852, 200.0]
print listdata [0][0]
>>>387.93852

Upvotes: 0

idjaw
idjaw

Reputation: 26600

You are looking to strip the new line character from each line, which you can easily do using the available strip method of str:

When you get your data in searchlines, do:

searchlines[i+1].strip()

To see that it is actually removed, check the repr:

 print(repr(P))

You can even do that repr print before and after applying the strip() to see what happened when calling that strip.

Considering the structure of the text you have, you are looking to make it a list, so, you could use loads from json to do this:

json.loads(searchlines[i+1].strip())

Upvotes: 2

KIDJourney
KIDJourney

Reputation: 1240

You can use str.strip() to remove the \n

for i, line in enumerate(searchlines):
    if "PointXY" in line:
        P = searchlines[i+1].strip()
        print(P)

Upvotes: 2

Related Questions