I'm trying to compare the file size in Python, but what's more efficient?

Asked 2 years ago, Updated 2 years ago, 45 views

I'm trying to compare the size of some files in Python os.path.getsize(path) It's different from comparing it with this function f = open("~~~.txt", 'r') Would it be faster to read it and count it until the eof comes out on the loop door? I just think it's faster to use os.path.getsize, but I don't know exactly how this function works.TT

python file

2022-09-22 13:17

2 Answers

That's a natural question. It is fastest to use os.path.getsize.

os.path.getsize obtains information by calling os.stat internally.

Among the return values of os.stat, the st_size field is the os.path.getsize value.

https://docs.python.org/ko/3/library/os.html#os.stat

Python includes the builtin function, and the functions of the os module are implemented as c.

The builtin functions, for performance reasons, the os module is an os-related task, so you have to call the os api.

If you are interested in the actual implementation source, look at the posix_do_stat function at the link below.

https://github.com/python/cpython/blob/master/Modules/posixmodule.c

Ultimately, call fstat function GetFileInformationByHandle when *nix is windowed.

If you want a smaller overhead, you can call fstat, GetFileInformationByHandle directly to ctypes.


2022-09-22 13:17

I don't think it's a good idea to actually read a file just to measure it.


2022-09-22 13:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.