0

I'm reading from a file and basically I need to make the integers into a series of lists, but they're already broken up in the data file. So, there's forty lines with five numbers each in them in the format 1, 2, 3, 4, 5

I can't figure out how to translate this into a list that keeps the numbers as integers because I keep getting an error saying that the comma isn't an integer.

I tried splicing the data, thinking that would help, but I can't x.split() on dict or list or anything other than string but I don't know how to convert the file into a string!

I would appreciate any help!

  • Possible duplicate of https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters – tiberius Jun 23 '20 at 01:55
  • I thought it was different because it is reading from a file rather than being a string inherently.. If it was just a string value I think I could figure it out! – Oddosaurus Jun 23 '20 at 02:03
  • Got it. The answers given below show good examples of how to do that, or you could also checkout the [docs](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) – tiberius Jun 23 '20 at 02:18

2 Answers2

1

Something like this:

data = []
with open("myfile") as f:
    for line in f:
        data.append([int(x) for x in line.split(",")])
print(data)

For input file

1,2,3,4,5
6,7,8,9,10

gives:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

Tweak as required for exact output format required (e.g. use extend instead of append if you don't want the nested lists).

alani
  • 12,573
  • 2
  • 13
  • 23
0

One way to do it would be to read the file one character at a time with a for loop, then add an if statement to get rid of the commas:

F = open("test.txt", "r")
str_read = F.read()
your_list = []
for i in range(0,len(str_read)):
    character = str_read[i]

    if character == ",":
        continue
    else:
        your_list.append(int(character))
    
print(your_list)

This way if the current character is a comma, the loop continues, if it is not a comma, you can turn the string type number into an integer and append it to a list.

  • Two issues with this. Firstly you need to `continue` on newline, not just comma. Secondly and more seriously, it assumes that the file will only contain 1-digit numbers. If there is a longer number, then each digit will become a separate number in the output list. – alani Jun 23 '20 at 02:16
  • Very true, thanks! So I would need to rearrange it in a way where it would only append the number if it also had a comma after it, which would be more decisions than the code deserves :) – UrasGungorPhys Jun 23 '20 at 02:38
  • Well I guess that after reading a digit you could keep looping until you get to a comma or newline, and build up a longer string out of these characters. But you will just end up implementing what `split` will do for you more easily anyway. – alani Jun 23 '20 at 02:48