gab55
gab55

Reputation: 123

Read text file to list in python

I want to create a text file which contains positive/negative numbers separated by ','. i want to read this file and put it in data = []. i have written the code below and i think that it works well. I want to ask if you guys know a better way to do it or if is it well written thanks all

#!/usr/bin/python
if __name__ == "__main__":
        #create new file
        fo = open("foo.txt", "w")
        fo.write( "111,-222,-333");
        fo.close()
        #read the file
        fo = open("foo.txt", "r")
        tmp= []
        data = []
        count = 0
        tmp = fo.read() #read all the file

        for i in range(len(tmp)): #len is 11 in this case
            if (tmp[i] != ','):
                count+=1
            else:
                data.append(tmp[i-count : i]) 
                count = 0

        data.append(tmp[i+1-count : i+1])#append the last -333
        print data
        fo.close()

Upvotes: 0

Views: 269

Answers (3)

Anand Tripathi
Anand Tripathi

Reputation: 16136

To get the whole file content(numbers positive and negative) into list you can use split and splitlines

file_obj = fo.read()#read your content into string
list_numbers = file_obj.replace('\n',',').split(',')#split on ',' and newline
print list_numbers

Upvotes: 0

Kewl
Kewl

Reputation: 3417

Instead of looping through, you can just use split:

#!/usr/bin/python
if __name__ == "__main__":
        #create new file
        fo = open("foo.txt", "w")
        fo.write( "111,-222,-333");
        fo.close()
        #read the file
        with open('foo.txt', 'r') as file:
            data = [line.split(',') for line in file.readlines()]
        print(data)

Note that this gives back a list of lists, with each list being from a separate line. In your example you only have one line. If your files will always only have a single line, you can just take the first element, data[0]

Upvotes: 0

anairebis
anairebis

Reputation: 36

You can use split method with a comma as a separator:

fin = open('foo.txt')
for line in fin:
    data.extend(line.split(','))
fin.close()

Upvotes: 1

Related Questions