python 比较两个文件大小
时间: 2023-05-21 15:01:55 浏览: 43
可以使用 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')
相关问题
python比较两个文本文件内容是否相同
可以使用Python内置的文件操作函数来比较两个文本文件内容是否相同。具体实现可以使用以下步骤:
1. 使用Python内置的`open()`函数打开两个文件,并分别使用`read()`函数读取文件内容,将内容存储到两个变量中。
2. 使用Python内置的`==`比较运算符比较两个变量是否相同,如果相同,则说明两个文件内容相同,否则不相同。
以下是一个简单的示例代码:
```python
with open('file1.txt', 'r') as file1:
content1 = file1.read()
with open('file2.txt', 'r') as file2:
content2 = file2.read()
if content1 == content2:
print('两个文件内容相同')
else:
print('两个文件内容不同')
```
在实际使用中,还需要注意文件编码、文件大小等因素对比较结果的影响。
帮我python创建一个模块文件,用于比较两个数的大小
好的,你可以按照以下步骤创建一个比较两个数大小的模块文件:
1. 打开文本编辑器,新建一个文件,命名为 `compare.py`(文件名可以自定义)。
2. 在 `compare.py` 中添加以下代码:
```python
def compare(num1, num2):
if num1 > num2:
return f"{num1} is greater than {num2}"
elif num1 < num2:
return f"{num1} is less than {num2}"
else:
return f"{num1} and {num2} are equal"
```
3. 保存 `compare.py` 文件。
现在你已经创建了一个比较两个数大小的模块文件。你可以在其他 Python 脚本中导入该模块,并使用其中的 `compare()` 函数。例如,假设你有一个 `main.py` 文件,想要比较两个数 `a` 和 `b` 的大小,可以这样写:
```python
from compare import compare
a = 5
b = 10
result = compare(a, b)
print(result)
```
输出结果为:
```
5 is less than 10
```