python遍历文件夹下TXT文件
时间: 2024-10-12 19:10:40 浏览: 41
在Python中,遍历文件夹下的所有TXT文件通常可以使用os和glob模块。以下是一个基本示例:
```python
import os
import glob
def traverse_directory(directory):
for filename in glob.glob(os.path.join(directory, '*.txt')):
with open(filename, 'r') as file:
print(f"打开文件: {filename}")
# 这里你可以读取文件内容,例如:
content = file.read()
print(content)
# 要遍历的目录路径替换为你需要的
traverse_directory('/path/to/your/directory')
```
这个函数会查找指定目录下所有的`.txt`文件,并对每个找到的文件打开并读取其内容。如果你想处理每个文件的内容,只需替换`print(content)`部分即可。
相关问题
python遍历文件夹下的txt文件
在Python中,你可以使用`os`和`glob`模块来遍历指定目录下的所有`.txt`文件。这里是一个简单的示例:
```python
import os
import glob
def traverse_folder(directory):
for filename in glob.glob(os.path.join(directory, '*.txt')):
with open(filename, 'r') as file:
print(f"打开文件: {filename}")
# 这里可以添加读取文件内容的代码
content = file.read()
print(content)
# 使用函数并提供你要遍历的文件夹路径
traverse_folder('/path/to/your/directory')
```
在这个例子中,`os.path.join(directory, '*.txt')`会生成一个包含目录下所有.txt文件完整路径的列表。然后我们逐个打开这些文件,并读取其内容。
python 遍历文件夹下的文件
Python可以使用os模块来遍历文件夹下的文件。可以使用os.listdir()方法来获取文件夹下的所有文件和文件夹,然后使用os.path.join()方法将文件夹路径和文件名拼接起来,得到文件的完整路径。接着可以使用os.path.isfile()方法判断是否是文件,如果是文件则输出文件的绝对路径,如果是文件夹则进行递归调用自定义函数,继续遍历该文件夹下的所有文件。以下是一个示例代码:
```
import os
from os import path
def scaner_file(url):
file = os.listdir(url)
for f in file:
real_url = path.join(url, f)
if path.isfile(real_url):
print(path.abspath(real_url))
elif path.isdir(real_url):
scaner_file(real_url)
else:
print("其他情况")
pass
scaner_file("D:\\")
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)