我想創建一個包含分隔正/負號的文本文件「」。 我想讀這個文件,並把它放在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