-1

here is my code right now:

from pathlib import Path

content = Path('numbers.txt').read_text()

for i in range(len(content)):
    content[i] = int(content[i])
    print(content)

the code doesn't work as of now

Corroshi
  • 5
  • 2
  • 3
    Are you familiar with `split()`? – Random Davis Jul 15 '21 at 20:15
  • An integer array (list) separated by a comma doesn't make sense: integers don't contain comma's. Either you mean *printing* them as integers with comma's in between, or you've seen comma's in output where they are just an artefact of the output, not of the actual list. – 9769953 Jul 15 '21 at 20:16
  • No, I am not. Is it something that can help me? – Corroshi Jul 15 '21 at 20:16
  • https://docs.python.org/3/library/stdtypes.html#str.split – 9769953 Jul 15 '21 at 20:17
  • 1
    Does this answer your question? ["pythonic" method to parse a string of comma-separated integers into a list of integers?](https://stackoverflow.com/questions/3477502/pythonic-method-to-parse-a-string-of-comma-separated-integers-into-a-list-of-i) Replace "comma" with "space". – Pranav Hosangadi Jul 15 '21 at 20:22

3 Answers3

1

Should be simple with split, unless I'm misunderstanding?

from pathlib import Path
content = Path('numbers.txt').read_text()
list_content = content.split()
integer_list = [int(x) for x in list_content]
print(integer_list)

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
0
from pathlib import Path

content = Path('numbers.txt').read_text()
listofnumbers = list(map(int, content.split()))

This code works by mapping the int function to the list of numbers in content.

Edit: Had a bug in my code it should be fixed now.

0

Unfortunately you can't create a list of integers, but you can create a list of 'numbers'. If that works, you could try the following:

from pathlib import Path

content = Path('numbers.txt').read_text().split(" ")
print(content)

The split(" ") splits the numbers in the file by the space in the quotes. Then it adds each of these 'splits' to an array.

If you need to keep it as an integer, you could instead use something like this:

content = Path('numbers.txt').read_text().split(" ")
for n in content:
    print((int(n))
    # Execute your code here but use the int() method to convert it back to an integer

For this you'll need to execute your code each time it splits the numbers.

Luke
  • 226
  • 1
  • 10