0

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?

4
  • 1
    what happens when you do it this way? Do you get an error message / traceback? I'd suggest print(txt) to see what this object actually is. Commented Jun 9, 2022 at 20:23
  • 1
    have you looked up "how to read a text file into a numpy array"? Commented Jun 9, 2022 at 20:35
  • @JacobIRR the message was "ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 7 but received input with shape (None, 1)". Yes, i used print(txt) and it showed 5,7,1,1,6,7,27. When print(new) it showed [['5,7,1,1,6,7,27']] Commented Jun 10, 2022 at 13:34
  • @juanpa.arrivillaga Hi! Yes, thank you, but I did a thorough search but yielded unsatisfactory results. Commented Jun 10, 2022 at 13:51

1 Answer 1

2

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(',')]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.