我想创建一个包含分隔正/负号的文本文件“”。 我想读这个文件,并把它放在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()
请参阅[CodeReview.SE]获取有关工作代码的反馈。 – JETM