突然间,我对巨蟒这种奇怪的行为感到很沮丧。我一直在给文件写各种各样的数据,但从今天早上开始似乎就没用了。在发布之前我已经提到了所有这些:
How to redirect 'print' output to a file using python?
Failed to write to file but generates no Error
Unable to write data into a file using python
Unable to write list of elements to a file using python
尝试了以下所有命令,但它只是没有向delete.txt文件写入任何内容。怎么了?
fl=open('delete.txt','w')
fl.write(msg) <--Doesnt work,tried this also
fl.write('%s' %msg) <--Doesnt work,tried this also
fl.write("at least write this") <-- Doesnt work,tried this also
print (msg) <- WORKS
代码:
for i in hd_com.comment_message[1:500]:
fl=open('delete.txt','wb')
try:
if len(i)>40:
mes=processComUni(i)
proc=nltk.tokenize.word_tokenize(mes)
#print proc
pos=nltk.pos_tag(proc)
for i in pos:
if ((i[1]=="NN") or (i[1]=="NNP") or (i[1]=="NNS")) and len(i[0])>2:
#print i[0],i[1]
for j in home_depo_inv:
if i[0] in j.split() and (i[0]!='depot' and i[0]!='home' and i[0]!='store' and i[0]!='por' and i[0]!='get' and i[0]!='house' and i[0]!='find' and i[0]!='part' and i[0]!='son' and i[0]!='put' and i[0]!='lot' and i[0]!='christmas' and i[0]!='post'):
a=re.findall(i[0],j)
fl.write(str(i))<--Doesnt work,tried this also
fl.write(str(mes))<--Doesnt work,tried this also
fl.write("\n")<--Doesnt work,tried this also
fl.write("hello")<--Doesnt work,tried this also
fl.flush()
break
except:
continue
fl.close()
更多代码:
type(mes) = str
mes="omg would love front yard"
最佳答案
您的代码片段缩进完全混乱,但无论如何:您的代码以:
for i in hd_com.comment_message[1:500]:
fl=open('delete.txt','wb')
这意味着您在每次迭代时重新打开文件进行写入,删除上一次迭代可能写入的内容。