如何在Python中确定打开文件的大小?

Jas*_*ker 10 python linux filesystems file ext2

有一个文件,我想确保不会超过2 GB(因为它必须在使用ext 2的系统上运行).检查文件大小的好方法是什么,记住我将在两次检查之间写入此文件?特别是,我是否需要担心尚未写入磁盘的缓冲,未刷新的更改?

Dom*_*mra 17

也许不是你想要的,但无论如何我都会建议.

import os
a = os.path.getsize("C:/TestFolder/Input/1.avi")
Run Code Online (Sandbox Code Playgroud)

或者对于打开的文件,您可以使用fstat函数,该函数可用于打开的文件.它需要一个整数文件句柄,而不是文件对象,因此您必须在文件对象上使用fileno方法:

a = open("C:/TestFolder/Input/1.avi")
b = os.fstat(a.fileno()).st_size
Run Code Online (Sandbox Code Playgroud)


D.S*_*ley 6

os.fstat(file_obj.fileno()).st_size应该做的伎俩.我认为它将返回写入的字节.如果您担心缓冲,可以随时进行冲洗.


Tre*_*ton 5

虽然这是一个老问题,但我认为 Isak 有最简单的解决方案。以下是在 Python 中执行此操作的方法:

# Assuming f is an open file
>>> pos = f.tell()  # Save the current position
>>> f.seek(0, 2)  # Seek to the end of the file
>>> length = f.tell()  # The current position is the length
>>> f.seek(pos)  # Return to the saved position
>>> print length
1024
Run Code Online (Sandbox Code Playgroud)


jcd*_*yer 4

你可以从这样的事情开始:

\n\n
class TrackedFile(file):\n    def __init__(self, filename, mode):\n        self.size = 0\n        super(TrackedFile, self).__init__(filename, mode)\n    def write(self, s):\n        self.size += len(s)\n        super(TrackedFile, self).write(s)\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后你可以像这样使用它:

\n\n
>>> f = TrackedFile('palindrome.txt', 'w')\n>>> f.size\n0\n>>> f.write('A man a plan a canal ')\n>>> f.size\n21\n>>> f.write('Panama')\n27\n
Run Code Online (Sandbox Code Playgroud)\n\n

显然,如果您不是从头开始编写文件,则此实现不起作用,但您可以调整__init__方法来处理初始数据。您可能还需要重写一些其他方法:writelines例如。

\n\n

无论编码如何,这都有效,因为字符串只是字节序列。

\n\n
>>> f2 = TrackedFile('palindrome-latin1.txt', 'w')\n>>> f2.write(u'A man a plan a can\xc3\xa1l '.encode('latin1')\n>>> f3 = TrackedFile('palindrome-utf8.txt', 'w')\n>>> f3.write(u'A man a plan a can\xc3\xa1l '.encode('utf-8'))\n>>> f2.size\n21\n>>> f3.size\n22\n
Run Code Online (Sandbox Code Playgroud)\n