1

I'm working on some code (that I have been given), as part of a coursework at University.

Part of the code requires that, we check the file we are writing to contains any data.
The file has been opened for writing within the code already:

f = open('newfile.txt', 'w')

Initially, I thought that I would just find the length of the file, however if I try: len(f)>512, I get an error:

TypeError: object of type 'file' has no len()

I have had a bit of a google and found various links, such as here, however when I try using the line: os.stat(f).st_size > 512, I get the following error message:

TypeError: coercing to Unicode: need string or buffer, file found

If I try and use the filename itself: os.stat("newfile.txt").st_size > 512, it works fine.

My question is, is there a way that I can use the variable that the file has been assigned to, f, or is this just not possible?

For context, the function looks like this:

def doData ():
global data, newblock, lastblock, f, port
if f.closed:
    print "File " + f.name + " closed"
elif os.stat(f).st_size>512:
    f.write(data)
    lastblock = newblock
    doAckLast()

EDIT: Thanks for the link to the other post Morgan, however this didn't work for me. The main thing is that the programs are still referencing the file by file path and name, whereas, I need to reference it by variable name instead.

Community
  • 1
  • 1
James
  • 117
  • 6
  • 3
    Once you open a file with `'w'`, you are deleting all contents of the file. You have to check *before* you open the file for writing. Because of that, you can't use `f` to check. – zondo Feb 25 '16 at 15:04
  • Possible duplicate of [python how to check file empty or not](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not) – Morgan Thrapp Feb 25 '16 at 15:04
  • `f.tell()` can be used to read the file position and tell if the file has already had some data written to it, but as @zondo said, the file is truncated when open for write. – Mark Tolonen Feb 25 '16 at 15:13

1 Answers1

1

According to effbot's Getting Information About a File page,

The os module also provides a fstat function, which can be used on an opened file. It takes an integer file handle, not a file object, so you have to use the fileno method on the file object:

This function returns the same values as a corresponding call to os.stat.

f = open("file.dat")
st = os.fstat(f.fileno())

if f.closed:
    print "File " + f.name + " closed"
elif st.st_size>512:
    f.write(data)
    lastblock = newblock
    doAckLast()
Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53