我正在编写一些代码(我已经得到了),作为大学类(class)的一部分。
部分代码要求我们检查正在写入的文件是否包含任何数据。
文件已在代码中打开以进行写入:
f = open('newfile.txt', 'w')
最初,我以为我只会找到文件的长度,但是如果我尝试:len(f)>512
,我会收到错误:
TypeError: object of type 'file' has no len()
我进行了一些谷歌搜索,找到了各种链接,例如here ,但是当我尝试使用以下行:os.stat(f).st_size > 512
时,我收到以下错误消息:
TypeError: coercing to Unicode: need string or buffer, file found
如果我尝试使用文件名本身:os.stat("newfile.txt").st_size > 512
,它工作正常。
我的问题是,有没有办法可以使用文件已分配给的变量,f
,或者这是不可能的?
就上下文而言,该函数如下所示:
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()
编辑:感谢您提供摩根其他帖子的链接,但这对我不起作用。主要的是程序仍然通过文件路径和名称引用文件,而我需要通过变量名称引用它。
最佳答案
根据 effbot 的 Getting Information About a File页面,
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()
关于python - 检查分配给 Python 2 中变量的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35630882/