python 判断一个文件是否有内容
时间: 2024-05-07 12:17:33 浏览: 12
可以使用Python的os模块中的stat()函数和文件的st_size属性来判断文件是否有内容。具体代码如下:
```python
import os
def is_file_empty(file_path):
return os.stat(file_path).st_size == 0
if is_file_empty('file.txt'):
print('文件为空')
else:
print('文件非空')
```
其中,file_path是待判断的文件路径。如果文件为空,则返回True,否则返回False。
相关问题
如何用python判断一个文件是否存在
您可以使用Python中的os模块进行文件存在性判断。具体的代码如下:
```
import os
if os.path.isfile('文件路径'):
print('文件存在')
else:
print('文件不存在')
```
请注意替换代码中的“文件路径”,改为您需要判断的文件路径。
python实现:判断文件是否有新内容写入
可以通过记录文件的修改时间来判断文件是否有新内容写入。具体实现代码如下:
```python
import os
import time
def check_file_updated(filename):
"""
判断文件是否有新内容写入
:param filename: 文件名
:return: True or False
"""
if not os.path.exists(filename):
return False
# 获取文件的修改时间
file_modified_time = os.path.getmtime(filename)
# 等待一定时间
time.sleep(5)
# 再次获取文件的修改时间
new_file_modified_time = os.path.getmtime(filename)
# 判断文件是否有新内容写入
return new_file_modified_time > file_modified_time
```
使用方法:
```python
if check_file_updated('test.txt'):
print('文件有新内容写入')
else:
print('文件没有新内容写入')
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)