Printing to a file via Python -
hopefully easy fix. i'm trying edit 1 field of file use import, when run following code leaves file blank , 0kb. advise i'm doing wrong?
import re #import regex can use commands name = raw_input("enter filename:") #prompt file name, press enter open test.nhi if len(name) < 1 : name = "test.nhi" count = 0 fhand = open(name, 'w+') line in fhand: words = line.split(',') #obtain individual words using split words[34] = re.sub(r'\d', "", words[34]) #remove non-numeric chars string using regex if len(words[34]) < 1 : continue # if 34th field blank go next line elif len(words[34]) == 2 : "{0:0>3}".format([words[34]]) #add leading zeroes depending on length of field elif len(words[34]) == 3 : "{0:0>2}".format([words[34]]) elif len(words[34]) == 4 : "{0:0>1}".format([words[34]]) fhand.write(words) #write line fhand.close() # close file after loop ends
i have taken below text in 'a.txt' input , modified code. please check if it's work you.
#intial content of a.txt this,program,is,java,program this,program,is,12python,programs
modified code follow:
import re #reading file , updating values fhand = open('a.txt', 'r') tmp_list=[] line in fhand: #split line using ',' words = line.split(',') #remove non-numeric chars 34th string using regex words[3] = re.sub(r'\d', "", words[3]) #update 3rd string # if 3rd field blank go next line if len(words[3]) < 1 : #removed continue here need reconstruct original line , write file print "field empty.continue..." elif len(words[3]) >= 1 , len(words[3]) < 5 : #format won't add leading zeros. zfill(5) add required number of leading zeros depending on length of word[3]. words[3]=words[3].zfill(5) #after updating 3rd value in words list, again creating line out of it. tmp_str = ",".join(words) tmp_list.append(tmp_str) fhand.close() #writing same file whand = open("a.txt",'w') val in tmp_list: whand.write(val) whand.close()
file content after running code
this,program,is,,program this,program,is,00012,programs
Comments
Post a Comment