Printing to stdout but unable to write a file in Python

I'm really disappointed with this strange Python behavior all of a sudden. I wrote all kinds of data to files, but since this morning it just doesn't work. I mentioned all of this before posting:

Have tried all of the following commands but it doesn't write anything to the delete.txt file. What's happening?

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

      

code:

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()

      

More code:

type(mes) = str
mes="omg would love front yard"

      

+3


source to share


2 answers


The indentation of your snippet is completely messed up, but anyway: your code starts with:

for i in hd_com.comment_message[1:500]:
    fl=open('delete.txt','wb')

      



which means that you re-open the file for writing at each iteration, erasing anything that may have been written by the previous iteration.

+4


source


You must explicitly clear the output stream when writing to the file descriptor.

f = open("test.txt", "w")
f.write("this is a test\n")
# no text in the output file at this point
f.flush()
# buffers are flushed to the file
f.write("this, too, is a test\n")
# again, line doesn't show in the file
f.close()
# closing the file flushes the buffers, text appears in file

      



From the file.write file documentation:

Note that due to buffering, flush () or close () may be necessary before the file on disk reflects the written data.

+2


source







All Articles