0

Hopefully this is an easy fix. I'm trying to edit one field of a file we use for import, however when I run the following code it leaves the file blank and 0kb. Could anyone advise what I'm doing wrong?

import re #import regex so we can use the commands

name = raw_input("Enter filename:") #prompt for file name, press enter to just open test.nhi
if len(name) < 1 : name = "test.nhi"
count = 0
fhand = open(name, 'w+')
for line in fhand:

  words = line.split(',') #obtain individual words by using split

  words[34] = re.sub(r'\D', "", words[34]) #remove non-numeric chars from string using regex

  if len(words[34]) < 1 : continue # If the 34th field is blank go to the next line
  elif len(words[34]) == 2 : "{0:0>3}".format([words[34]]) #Add leading zeroes depending on the length of the 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 the line
fhand.close() # Close the file after the loop ends
2
  • Maybe the w+ file setting is messing with it. Try w or a. Also, .format() does not do the operation in place. .format() actually returns the formatted value. Commented Aug 25, 2015 at 0:18
  • You are trying to write to a file while you are reading. Will you loop exit? Commented Aug 25, 2015 at 2:27

4 Answers 4

1

I have taken below text in 'a.txt' as input and modified your code. Please check if it's work for you.

#Intial Content of a.txt
This,program,is,Java,program
This,program,is,12Python,programs

Modified code as follow:

import re 

#Reading from file and updating values
fhand = open('a.txt', 'r')
tmp_list=[]
for line in fhand:
  #Split line using ','
    words = line.split(',') 
  #Remove non-numeric chars from 34th string using regex
    words[3] = re.sub(r'\D', "", words[3])
  #Update the 3rd string
    # If the 3rd field is blank go to the next line
    if len(words[3]) < 1 :
        #Removed continue it from here we need to reconstruct the original line and write it to file
        print "Field empty.Continue..." 
    elif len(words[3]) >= 1 and len(words[3]) < 5 :
       #format won't add leading zeros. zfill(5) will add required number of leading zeros depending on the length of word[3].
        words[3]=words[3].zfill(5)

    #After updating 3rd value in words list, again creating a line out of it.
    tmp_str = ",".join(words)
    tmp_list.append(tmp_str)
fhand.close()

#Writing to same file
whand = open("a.txt",'w')
for val in tmp_list:
    whand.write(val)
whand.close()

File content after running code

This,program,is,,program
This,program,is,00012,programs
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Sorry for the late reply, I've been away without internet access for a while. Thanks for your replies Dinesh your solution is perfect, thanks
1

The file mode 'w+' Truncates your file to 0 bytes, so you'll only be able to read lines that you've written.

Look at Confused by python file mode "w+" for more information.

An idea would be to read the whole file first, close it, and re-open it to write files in it.

Comments

0

Not sure which OS you're on but I think reading and writing to the same file has undefined behaviour.

I guess internally the file object holds the position (try fhand.tell() to see where it is). You could probably adjust it back and forth as you went using fhand.seek(last_read_position) but really that's asking for trouble.

Also, I'm not sure how the script would ever end as it would end up reading the stuff it had just written (in a sort of infinite loop).

Best bet is to read the entire file first:

with open(name, 'r') as f:
    lines = f.read().splitlines()

with open(name, 'w') as f:
    for l in lines:
        # ....
        f.write(something)

Comments

0

For 'Printing to a file via Python' you can use:

ifile = open("test.txt","r")
print("Some text...", file = ifile)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.