2017-03-06 168 views
0

我想创建一个包含分隔正/负号的文本文件“”。 我想读这个文件,并把它放在data = []。我已经编写了下面的代码,我认为它运行良好。 我要问你们是否知道一个更好的方式来做到这一点,或者如果它做好循环通过书面 感谢所有阅读文本文件列出在python

#!/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() 
+3

请参阅[CodeReview.SE]获取有关工作代码的反馈。 – JETM

回答

1

您可以使用split方法用逗号作为分隔符:

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

感谢您的帮助,我需要追加数为float进一步code..i试图data.extend(浮点(line.split(“”)),但它似乎没有工作。我需要这样的data.append (float(tmp [i-count:i])) – gab55

+0

line.split(',')返回一个列表,并且不能将float直接应用到列表中。如果要将其应用于该列表的每个元素你可以使用map方法: data.extend(map(float,line.split(','))) 或者你为了更好地理解它,map(float,line.split(','))表示[float(num)for num in line.split(',')] – anairebis

0

相反,你可以只使用分裂:

#!/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) 

注这给出了一个列表的列表,每个列表来自一个单独的行。在你的例子中,你只有一行。如果你的文件将始终只有一个单一的线,你可以采取的第一个元素,数据[0]

0

要获得全文件内容(数字正数和负数)到列表中,您可以使用分割和分割线

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