python 将素材中data文件夹复制到c盘更目录下,在路径c:\data下,利用os模块函数输出所有文件名,再利用re模块函数输出txt文件,最后统计txt文件的个数,输出结果。。
时间: 2024-03-11 07:49:19 浏览: 27
好的,要实现这个功能,需要使用到 `os` 模块和 `re` 模块。以下是代码实现:
```python
import os
import re
# 复制文件夹到指定目录
src_dir = './data'
dst_dir = 'C:/data'
os.system('xcopy /e /y {} {}'.format(src_dir, dst_dir))
# 输出所有文件名
file_list = os.listdir(dst_dir)
print("所有文件名:")
for filename in file_list:
print(filename)
# 输出所有 txt 文件名
txt_list = [filename for filename in file_list if re.match('.*\.txt', filename)]
print("所有 txt 文件名:")
for filename in txt_list:
print(filename)
# 统计 txt 文件数量
txt_count = len(txt_list)
print("txt 文件数量:", txt_count)
```
输出结果:
```
所有文件名:
file1.txt
file2.png
file3.txt
file4.docx
所有 txt 文件名:
file1.txt
file3.txt
txt 文件数量: 2
```
解释一下代码:我们首先使用 `os.system()` 函数调用系统命令 `xcopy` 复制文件夹,将 `./data` 文件夹复制到 `C:/data` 文件夹下。然后使用 `os.listdir()` 函数获取 `C:/data` 文件夹下所有文件的文件名,遍历输出所有文件名。接着使用列表推导式和正则表达式,筛选出所有扩展名为 `.txt` 的文件名,遍历输出这些文件名。最后使用 `len()` 函数获取 `txt_list` 列表的长度,即为 txt 文件的数量。
希望能够帮到你!
相关推荐
![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)