python查看一个文件的大小
时间: 2023-11-27 09:51:09 浏览: 37
你可以使用Python内置的os模块来获取文件大小。下面是一个示例代码:
```python
import os
file_path = "/path/to/your/file"
size = os.path.getsize(file_path)
print("File size in bytes:", size)
```
你需要将 `file_path` 替换为你要查看大小的文件的路径。 运行以上代码将在控制台输出文件的大小(以字节为单位)。
相关问题
用python写一个查看文件夹大小的代码
你可以使用以下代码来获取文件夹的大小:
```python
import os
def get_size(path='.'):
total = 0
with os.scandir(path) as it:
for entry in it:
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_size(entry.path)
return total
print(get_size())
```
在这个代码中,`get_size` 函数会遍历文件夹中的所有文件和子文件夹,并将它们的大小累加起来。最后返回累加的大小。调用 `get_size()` 函数时,传入要查看的文件夹路径即可。如果没有传入任何参数,则默认查看当前文件夹的大小。
python 比较两个文件大小
可以使用 os 模块中的 stat() 函数获取文件大小信息,然后进行比较。具体代码如下:
import os
file1 = 'path/to/file1'
file2 = 'path/to/file2'
size1 = os.stat(file1).st_size
size2 = os.stat(file2).st_size
if size1 > size2:
print(f'{file1} is larger than {file2}')
elif size1 < size2:
print(f'{file2} is larger than {file1}')
else:
print(f'{file1} and {file2} are of the same size')
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)