6

I know this question has been asked before quiet a lot on SO and elsewhere too. I still couldn't get it done. And im sorry if my English is bad

Removing file in linux was much more simpler. Just os.remove(my_file) did the job, But in windows it gives

    os.remove(my_file)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: (file-name)

my code :

line_count = open(my_file, mode='r')        #
t_lines = len(line_count.readlines())       # For total no of lines
outfile = open(dec_file, mode='w')
with open(my_file, mode='r') as contents:
    p_line = 1
    line_infile = contents.readline()[4:]
    while line_infile:
        dec_of_line = baseconvert(line_infile.rstrip(),base16,base10)
        if p_line == t_lines:
            dec_of_line += str(len(line_infile)).zfill(2)
            outfile.write(dec_of_line + "\r\n")
        else:
            outfile.write(dec_of_line + "\r\n")
        p_line += 1
        line_infile = contents.readline()[4:]
outfile.close()
os.remove(my_file)

Here my_file is a variable that contains complete path structure of a file. Like wise dec_file also contains path, but to a new file. And the file im trying to remove is the file that's being used under read mode. Need some help please.

my try's :

  1. Tried closing the file my_file.close(). The corresponding error i got was AttributeError: 'str' object has no attribute 'close'. I knew, when a file is in read mode it automatically closes when it comes to the end of the file. But still i gave it a try
  2. Also tried by os.close(my_file) as per https://stackoverflow.com/a/1470388/3869739. i got error as TypeError: an integer is required
  3. Or, am i getting this error just because i have opened the file twice (for counting the line and to read the file content),..?
Community
  • 1
  • 1
arvindh
  • 739
  • 4
  • 12
  • 28
  • code look fine, what is written inside with statement i.e. in do somthing ?? – Vivek Sable Feb 08 '15 at 17:20
  • @VivekSable ,..I edited the code,.. this is my complete code. It dose a baseconversion from a file and paste it inside another file. – arvindh Feb 08 '15 at 17:29
  • @eryksun ,. i didn't get what you mentioned,.. can you please explain `"Just use the single contents file object in the with statement"`. – arvindh Feb 08 '15 at 17:37
  • @eryksun ,. It Worked,.. Thanks a lot,.. Now how should i select/accept this as an answer,..? Will you make a separate answer,..? – arvindh Feb 08 '15 at 18:22

1 Answers1

5

Pythonic way of reading from or writing to a file is by using a with context.

To read a file:

with open("/path/to/file") as f:
    contents = f.read()
    #Inside the block, the file is still open

# Outside `with` here, f.close() is automatically called.

To write:

with open("/path/to/file", "w") as f:
    print>>f, "Goodbye world"

# Outside `with` here, f.close() is automatically called.

Now, if there's no other process reading or writing to the file, and assuming you have all the permission you should be able to close the file. There is a very good chance that there's a resource leak (file handle not being closed), because of which Windows will not allow you to delete a file. Solution is to use with.


Further, to clarify on few other points:

  • Its the garbage collector that causes the closure of the stream when the object is destroyed. The file is not auto-closed upon complete reading. That wouldn't make sense if the programmer wanted to rewind, would it?
  • os.close(..) internally calls the C-API close(..) that takes an integer file descriptor. Not string as you passed.
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
  • I used the with statements as you said,.. `with open(dec_file, mode='w') as outfile, open(my_file, mode='r') as contents:` and the `do something` followed with `os.remove(my_file)` I still get the same `[Error 32]` – arvindh Feb 08 '15 at 18:09
  • That means there's a file really open elsewhere. 1) Are you able to delete from a terminal ? 2) Are you able to delete it from another python script that does not open the file at all ? – UltraInstinct Feb 08 '15 at 18:14
  • 2
    You've opened the file twice (first and fourth lines) so presumably you need to close it twice. If the `with` automatically closes that instance, you just need a `line_count.close()` to close the other one. – Harry Johnston Feb 08 '15 at 20:06