Gary Gary - 1 year ago 60
Python Question

Reading in a text file, and separating the string by bracket in Python

I have a text file that I am feeding with data as a string, using the following lines of Python:

file = open("C:\\Users\\Me\\Desktop\\data.txt", "a")
file.writelines(str(mathfunction(readField())))
file.flush()
file.close()


in the format as follows:

enter image description here

Every input into the text file consists of an array of three items.

My goal is to extract the third item from each input, convert it to a float, and then store these values in a new array. So, ideally, in the above case, the array would contain:

[1.0087890625, 0.4404296875, 0.4404296875]


I tried the following:

data = pd.read_csv("C:\\Users\\User\\Desktop\\data.txt", sep="]", header = None)
data.head()


enter image description here

and it returned the data in what looks like a string format.

What are the next steps that I should take, in order to isolate the third item in each subarray, and store it all in one array?

EDIT: Here is some data from data.txt

[0.0263671875, 0.03515625, 1.0087890625][0.01171875, 0.0146484375, 0.4404296875][0.01171875, 0.0146484375, 0.4404296875]

Answer Source

You can then split by ',' commas after reading in the data:

data = pd.read_csv("C:\\Users\\User\\Desktop\\data.txt", sep="]", header = None)
data = data.iloc[0]
data = data.apply(lambda x: x.split(',')[2]).astype(float).tolist()

If you want to keep the data in a Pandas Series, just remove the tolist() portion above. Here is an example:

data = pd.DataFrame([['[1,2,3','[3,4,5','[4,5,6']])
print(data)
        0       1       2
0  [1,2,3  [3,4,5  [4,5,6

data = data.iloc[0]
data = data.apply(lambda x: x.split(',')[2]).astype(float).tolist()
print(data)
[3.0, 5.0, 6.0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download