R.Mckemey
R.Mckemey

Reputation: 355

How can I check if a tar file can be written to using the tarfile module?

I'm looking to append to a .tar file using tarfile but I don't know if the file is in use or not. How can I check to see if the file can be appended to?

I've tried:

try:
   with tarfile.open("foo.tar", "a:") as tar:
      tar.add("bar.txt")
except tarfile.TarError:
   print "error"

and this will sometimes get the error but sometimes it doesn't and the tar file at the end doesn't have all the files I'd expect.

My plan is to have this in a loop and keep trying until it works.

I have other options most of which involve leaving the taring to another process but I feel that tarfile should be responsible for this sort of thing. I could write a wrapper for tarfile that checks the new file appears on the tar.getmembers() list.

Upvotes: 1

Views: 144

Answers (1)

o11c
o11c

Reputation: 16056

The only safe way to do this is:

  • Make a copy of the file.
  • Open the copy in append mode.
  • Rename the copy over the original.

Upvotes: 2

Related Questions