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.
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()