python实现将d盘下名为1,3,7,11的几个文件夹中的check文件夹中的x.txt读取,并依次打印最后一行信息
时间: 2023-05-23 21:01:14 浏览: 40
可以使用以下代码实现:
```python
import os
folders = ["1", "3", "7", "11"]
for folder in folders:
path = os.path.join("D:\\", folder, "check", "x.txt")
with open(path, "r") as file:
lines = file.readlines()
print(lines[-1])
```
这段代码会将 D 盘下名为 1、3、7、11 的几个文件夹中的 check 文件夹中的 x.txt 文件依次读取,并输出它们的最后一行信息。
相关问题
python实现将d盘test文件夹下所有叫check的文件夹中的x.txt和y.txt两个文本文档的最后一行,输出到d盘test文件下的restult.txt中,并自动换行
可以使用os和glob模块来实现这个功能。以下是示例代码:
```python
import os
import glob
# 获取所有名字为check的文件夹路径
folders = glob.glob('D:/test/**/check', recursive=True)
# 遍历每个文件夹
for folder in folders:
# 获取x.txt和y.txt的路径
x_path = os.path.join(folder, 'x.txt')
y_path = os.path.join(folder, 'y.txt')
# 读取最后一行
with open(x_path, 'r') as f1, open(y_path, 'r') as f2:
x_last_line = f1.readlines()[-1]
y_last_line = f2.readlines()[-1]
# 将最后一行写入result.txt
with open('D:/test/result.txt', 'a') as f:
f.write(x_last_line.strip() + '\n')
f.write(y_last_line.strip() + '\n')
```
这段代码会搜索D盘test文件夹下所有名字为check的文件夹,并读取其中的x.txt和y.txt文件的最后一行,将它们写入D盘test文件夹下的result.txt中,并自动换行。
Python检查C盘和D盘路径下是否存在"test.txt"文件,如果不存在则不做动作,如果存在则检查"test.txt内是否包含"open"字符,如果包含,则不做动作,如果不包含则弹窗口警告"数据异常请联系工程师"需要实时监控
好的,以下是Python的代码实现:
```python
import os
def check_file(path):
if os.path.exists(path):
with open(path, 'r') as f:
content = f.read()
if 'open' not in content:
print('数据异常请联系工程师')
else:
pass # 文件不存在,不做动作
check_file('C:/test.txt')
check_file('D:/test.txt')
```
这段代码首先通过`os.path.exists`函数判断文件是否存在,如果不存在则不做动作,如果存在则打开文件并读取内容。如果文件内容中不包含`open`字符,则输出提示信息。如果包含,则不做动作。最后分别检查C盘和D盘下的`test.txt`文件。你可以将这段代码放在一个循环中,以实现实时监控。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)