strange newlines being inserted in python file write -


does have idea or know of situation python inserts newline characters strangely.

this piece of code

  if ((sentanalyze) , len(opstring)!=0):     if data[8]!= '':         if (data[8] == 'p'):             opstring = "1 " + opstring         elif (data[8] == 'n'):             opstring = "-1 " + opstring         elif (data[8] == 'neu'):             opstring = "0 " + opstring         print "writing :", opstring         fw.write(opstring + "\n") 

when try looking @ print commands , file write commands, there new line inserted in file line numbers.

this entire if block in while loop , print command prints lines properly.

and yeah opening file in w+ mode.

function (partially written here) compute opstring

 word,tag in simplified_tokens:                 tok = word + "/" + tag                 if tok in self.wordtoposition:                     opstring = opstring+ " " + str(self.wordtoposition[tok]) + ":1" #+ str(1.0 / self.uniqposhash[tok]) return opstring 

and data looks like

1981:1 503:1 21:1 58:1 159:1 1:1 87:1 412:1 105:1 478:1 1154:1 1023:1 1192:1 53:1 37:1 36:1 598:1 19:1 4:1 162:1 14:1 131:1 2:1 489:1 411:1 3:1 165:1 370:1   -17:1 614:1 6:1 631:1 59:1 1:1 0:1 1183:1 10:1 22:1 15:1 67:1 55:1 3:1 175:1 9:1 43:1 866:1 48:1 30:1 0:1 484:1 2:1 1106:1 109:1 

notice newline between. happening @ places.

repr(opstring) shows

'1981:1 503:1 21:1 58:1 159:1 1:1 87:1 412:1 105:1 478:1 1154:1 1023:1 1192:1 53:1 37:1 36:1 598:1 19:1 4:1 162:1 14:1 131:1 2:1 489:1 411:1 3:1 165:1 370:1' '-17:1 614:1 6:1 631:1 59:1 1:1 0:1 1183:1 10:1 22:1 15:1 67:1 55:1 3:1 175:1 9:1 43:1 866:1 48:1 30:1 0:1 484:1 2:1 1106:1 109:1' 

note. removing "\n" still add line when writing file lines. weird

another interesting observation. in above approach, reading file , writing different file. have 2 file handles open. fr file read , fw file write. if have fr open, build entire opstring variable, close fr , write using fw, not weird new lines. interesting!

we'd have see input data working .. in meantime, can try

fw.write(opstring.strip() + '\n') 

strip() strip errand newlines may have original data before appending 1 explicitly write.

i suspect @ least of opstrings have trailing newline already.

this not meant fix, diagnostic. once determine source of problem, better approach eliminate errand newlines @ origin/when read them.

update:

better yet, an

 opstring = opstring.strip() 

before enter if-statement per @kindall's helpful comment


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -