faraho
faraho

Reputation: 15

Place variable into array in Python

My text file has a single line that will be overwritten from time to time. The actual value is:

5,7,1,1,6,7,27

I want to read this *.txt and place its content inside a np.array, so that it would be:

new = np.array([[5,7,1,1,6,7,27]])

What I tried:

import numpy as np
from pathlib import Path
txt = Path('c:\MyFolder\myValue.txt').read_text()
new = np.array([[txt]])

How to correct this?

Upvotes: 0

Views: 42

Answers (1)

Alexander
Alexander

Reputation: 17291

Try this:
All I did was split the string by the ',' delimiter, then cast the values to int.

import numpy as np
from pathlib import Path
txt = Path('c:\MyFolder\myValue.txt').read_text()
new = np.array([[int(i) for i in txt.split(',')]])

Upvotes: 2

Related Questions