-1

I found this list of numbers that I have stored in a python document called "test.txt":

1 2
2 3
3 2
4 5
5 2
6 3
7 7
8 2
9 11
10 13
11 2
12 3
13 5
14 17
15 19
16 2
17 23
18 7
19 29
20 3
21 31
22 2
23 37
24 41
25 43
26 47
27 5
28 53
29 59
30 2

And I am trying to remove the first number of every line and put the second number in a list as an integer so it looks like this:

[2, 3, 2, 5, 2, 3, 7, 2, 11, 13, 2, 3, 5, 17, 19, 2, 23, 7, 29, 3, 31, 2, 37, 41, 43, 47, 5, 53, 59, 2]

I have tried this bit of code:

from inspect import currentframe, getframeinfo

frameinfo = getframeinfo(currentframe())

with open("test.py", "rt") as openfile:
   new_list = []
   for line in openfile:
       new_list.append(line.rstrip(str(frameinfo.lineno())))

print(new_list)

But it gives me this error:

Traceback (most recent call last):
  File "fileLocation", line 8, in <module>
    new_list.append(line.rstrip(str(frameinfo.lineno())))
TypeError: 'int' object is not callable

Does anyone have a solution for this problem?

Boopiester
  • 141
  • 1
  • 10
  • 4
    This isn't a valid python document. It's a csv in a misnamed file. – MisterMiyagi Dec 03 '19 at 07:39
  • 3
    Does this answer your question? [Delete or remove last column in CSV file using Python](https://stackoverflow.com/questions/7245738/delete-or-remove-last-column-in-csv-file-using-python) – MisterMiyagi Dec 03 '19 at 07:45
  • 3
    Do you actually have empty lines in your document or is this just from copying the document? – MisterMiyagi Dec 03 '19 at 07:53

4 Answers4

2

You could use re.sub here:

with open("test.py", "rt") as openfile:
    new_list = []
    for line in openfile:
        new_list.append(re.sub(r'^\d+\s+', '', line))

The pattern ^\d+\s+ would match the leading digit (and following whitespace) of any line which began with a line number.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Tim Biegeleisen's answer should work well.
Another simple approach is to split the line (after striping) using and taking the second element.

with open("test.py", "rt") as openfile:
    new_list = []
    for line in openfile:
        try:
            new_list.append(line.strip().split(' ')[1])
        except IndexError:
            pass

print(new_list)
Hrishi
  • 1,424
  • 1
  • 13
  • 29
0

One easy solution is to use numpy:

import numpy as np
x = np.genfromtxt('test.py')
new_list = x[:,1]
Solvalou
  • 1,133
  • 1
  • 10
  • 19
0

This will help you

new_list.append(line.rstrip(str(frameinfo.lineno())).split(" ")[1])
Nj Nafir
  • 570
  • 3
  • 13