python实现:判断D盘中文件a是否有新内容写入
时间: 2024-05-14 08:12:50 浏览: 23
以下是一个简单的Python程序,可以检查D盘中文件a是否有新内容写入:
```python
import os
import time
filename = 'D:\\a.txt'
last_size = 0
while True:
# 获取文件大小
size = os.path.getsize(filename)
# 如果文件大小发生变化,说明有新内容写入
if size > last_size:
print('文件有新内容写入')
last_size = size
# 等待1秒钟后再次检查
time.sleep(1)
```
此程序会不断循环检查文件大小,如果文件大小发生变化,则说明有新内容写入。注意,如果文件大小一直在变化,程序会一直输出“文件有新内容写入”,可以根据实际需求进行修改。
相关问题
python实现:判断文件D盘下文件a是否有新内容写入
可以使用os.path.getmtime()函数获取文件的最后修改时间,然后与之前记录的时间进行比较,如果最后修改时间比之前记录的时间要晚,则说明文件有新内容写入。
以下是示例代码:
```
import os
import time
file_path = 'D:/a.txt'
last_modified_time = os.path.getmtime(file_path)
while True:
current_modified_time = os.path.getmtime(file_path)
if current_modified_time > last_modified_time:
print('文件有新内容写入')
last_modified_time = current_modified_time
time.sleep(1) # 暂停1秒钟再检查文件是否有新内容写入
```
该程序每隔1秒钟检查一次文件的最后修改时间,如果发现最后修改时间比之前记录的时间要晚,则输出“文件有新内容写入”并更新记录的时间。
python实现:判断D盘下b文件夹下文件a是否有新内容写入
可以使用Python的os和time模块来实现判断D盘下b文件夹下文件a是否有新内容写入的功能。具体实现步骤如下:
1. 导入os和time模块。
```python
import os
import time
```
2. 获取文件a的路径。
```python
file_path = r'D:\b\a.txt'
```
3. 获取文件a的最后修改时间。
```python
last_modified_time = os.path.getmtime(file_path)
```
4. 进行轮询,每隔一定时间检查一次文件a是否有新内容写入。
```python
while True:
current_modified_time = os.path.getmtime(file_path)
if current_modified_time != last_modified_time:
print('文件a有新内容写入。')
last_modified_time = current_modified_time
time.sleep(5) # 每隔5秒检查一次文件a是否有新内容写入
```
完整代码如下:
```python
import os
import time
file_path = r'D:\b\a.txt'
last_modified_time = os.path.getmtime(file_path)
while True:
current_modified_time = os.path.getmtime(file_path)
if current_modified_time != last_modified_time:
print('文件a有新内容写入。')
last_modified_time = current_modified_time
time.sleep(5) # 每隔5秒检查一次文件a是否有新内容写入
```