用python遍历文件夹1,得到所有pdf文件的名称。遍历文件夹2中的所有txt文件名称,如果pdf文件的名称没有对应同名的txt文件名称,就在控制台输出pdf文件名称,反之不做任何操作。输出的pdf文件名称按照时间倒序排序。
时间: 2023-05-28 18:07:44 浏览: 101
以下是实现代码:
```python
import os
import glob
pdf_files = glob.glob("文件夹1/*.pdf")
pdf_names = [os.path.basename(file) for file in pdf_files]
txt_files = glob.glob("文件夹2/*.txt")
txt_names = [os.path.splitext(os.path.basename(file))[0] for file in txt_files]
pdf_names_without_txt = sorted(list(set(pdf_names) - set(txt_names)), reverse=True)
for name in pdf_names_without_txt:
print(name)
```
解释:
首先使用`glob`模块获取文件夹1中所有的pdf文件路径,然后使用`os.path.basename`函数获取每个文件的文件名,并存储在列表`pdf_names`中。
接着使用`glob`模块获取文件夹2中所有的txt文件路径,然后使用`os.path.splitext`函数获取每个文件的文件名(去掉扩展名),并存储在列表`txt_names`中。
使用`set`的差集运算得到在pdf文件夹中存在但是在txt文件夹中不存在的pdf文件名,存储在列表`pdf_names_without_txt`中。然后使用`sorted`函数按照时间倒序排序。
最后遍历`pdf_names_without_txt`列表,输出其中的每个元素(即pdf文件名)。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)