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
Chris
  • 357
  • 1
  • 3
  • 14
  • 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. –  Aug 25 '15 at 00:18
  • You are trying to `write` to a file while you are `reading`. Will you loop exit? – luoluo Aug 25 '15 at 02:27

4 Answers4

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.

Community
  • 1
  • 1
Nolan Akash
  • 989
  • 8
  • 21
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
Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • 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 – Chris Aug 28 '15 at 00:35
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)
Aidan Kane
  • 3,856
  • 2
  • 25
  • 28
0

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

ifile = open("test.txt","r")
print("Some text...", file = ifile)
Alessandro_Russo
  • 1,799
  • 21
  • 34