我想通过python抓取某个路径下的多个文件夹中的文件
时间: 2024-05-09 17:21:32 浏览: 9
可以使用Python的os库和glob库来实现。具体代码如下:
```python
import os
import glob
# 指定要抓取的文件夹路径
folder_path = "your/folder/path"
# 使用os库列出所有文件夹
folders = [f.path for f in os.scandir(folder_path) if f.is_dir()]
# 遍历每个文件夹,使用glob库获取文件列表
for folder in folders:
files = glob.glob(os.path.join(folder, "*"))
print(files)
```
这段代码可以获取指定路径下每个文件夹中的所有文件列表。
相关问题
Python抓取路径中多级文件夹内的txt文件合并成一个excel
以下是一个Python脚本示例,它可以抓取指定路径中多级文件夹内的所有txt文件并将它们合并为一个excel文件。
```python
import os
import glob
import pandas as pd
# 指定txt文件所在的路径
path = r'C:\your\path\to\directory'
# 获取所有txt文件的路径
txt_files = glob.glob(os.path.join(path, '**/*.txt'), recursive=True)
# 如果txt文件不存在,则退出程序
if not txt_files:
print('No txt files found in the specified directory')
exit()
# 通过循环读取每个txt文件并将它们合并到一个DataFrame中
data = pd.DataFrame()
for file in txt_files:
# 读取txt文件数据并转换为DataFrame
df = pd.read_csv(file, delimiter='\t')
# 添加文件名列
filename = os.path.splitext(os.path.basename(file))[0]
df['Filename'] = filename
# 将新的DataFrame合并到主DataFrame中
data = pd.concat([data, df])
# 将合并后的数据保存为excel文件
data.to_excel(os.path.join(path, 'merged_data.xlsx'), index=False)
```
此代码使用`glob`模块来查找指定路径内的所有txt文件。然后,它循环遍历这些文件并使用`pd.read_csv()`函数读取它们的内容。一个新的DataFrame被创建,并各个txt文件中的数据被添加到其中。最后,数据被保存为一个新的excel文件。请注意,代码中的分隔符为Tab。根据实际情况,您可能需要将其更改为适当的分隔符。
Python抓取一个路径下多个子文件夹下多个子文件夹中的txt,合并在一个excel中
以下是一个示例代码,展示如何使用Python抓取指定路径下多个子文件夹中的txt文件,并将它们合并到一个Excel文件中:
```python
import os
import pandas as pd
# 指定要抓取的文件路径
main_folder = r'C:\Users\username\Documents\example_folder'
# 遍历所有子文件夹,获取所有txt文件路径
txt_files = []
for root, dirs, files in os.walk(main_folder):
for filename in files:
if filename.endswith('.txt'):
txt_files.append(os.path.join(root, filename))
# 将所有txt文件读取为DataFrame,并将它们合并为一个DataFrame
dfs = []
for file in txt_files:
df = pd.read_csv(file, sep='\t') # 或者其他你想要的分隔符
dfs.append(df)
merged_df = pd.concat(dfs)
# 将合并的DataFrame保存为Excel文件
output_file = r'C:\Users\username\Documents\example_output.xlsx'
merged_df.to_excel(output_file, index=False)
```
这个代码将抓取指定路径下所有子文件夹中的txt文件,并将它们合并为一个Excel文件。你可以根据需要修改文件路径和分隔符。你可以将此代码保存为一个.py文件并在命令行或集成开发环境终端中运行它,或者将它放入一个Jupyter Notebook中运行。