0

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()
1
  • 3
    Please see Code Review for feedback on working code. Commented Mar 6, 2017 at 13:49

3 Answers 3

1

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

2 Comments

thanks for your help, i need to append the numbers as float for further code..i tried data.extend(float(line.split(',')) but it seems not to work. i need like this data.append(float(tmp[i-count : i]))
line.split(',') returns a list, and you can't apply float to the list directly. If you want to apply it to each element of that list you can use map method: data.extend(map(float, line.split(','))) or for you to better understand it, map(float, line.split(',')) means [float(num) for num in line.split(',')]
0

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]

Comments

0

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

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.