python - 检查分配给 Python 2 中变量的文件大小

标签 python python-2.7 variables filesize

我正在编写一些代码(我已经得到了),作为大学类(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/

相关文章:

python - 按列将函数应用于 Pandas 数据框

python - 为什么格式化会导致 print() 失败?

python - 为什么python看不到模块?

javascript - 从一个 javascript 文件调用变量到另一个

python - "inconsistent use of tabs and spaces in indentation"

javascript - 如何使用 pytherejs 导入外部几何图形

python - 构建路径 - Google Drive SDK

python - 为什么 python 2.7 的性能(剪影分数)比 3.6 更好?

python - 如何在两个线程之间共享一个变量

variables - 在 Coldfusion8 application.cfc 中哪里定义应用程序和 session 变量?