在Python中,你可以使用多种方法来处理多个文件。以下是一些常见的方法:
1. 使用循环创建多个文件
for i in range(10):with open(f'file_{i}.txt', 'w') as file:file.write(f'This is file number {i}\n')
2. 使用列表推导式创建多个文件
[with open(f'file_{i}.txt', 'w') as file:file.write(f'This is file number {i}\n') for i in range(10)]
3. 使用函数创建多个文件
def generate_files(num_files):for i in range(num_files):with open(f'file_{i}.txt', 'w') as file:file.write(f'This is file number {i}\n')generate_files(10) 生成10个文件
4. 合并多个文件
使用pandas模块
import pandas as pdfile1 = pd.read_csv('pink.csv', encoding='gbk')file2 = pd.read_csv('pimk2.csv', encoding='gbk')file3 = pd.merge(file1, file2, how='left', left_on='', right_on='')
5. 批量执行多个Python文件

使用subprocess模块
import subprocessfile_list = ['file1.py', 'file2.py', 'file3.py']for file in file_list:subprocess.run(['python', file])
使用命令行工具
for /r %F in (*.py) do python %F
6. 创建多个文件夹
import ospath = 'C:/EnglishLETS雅思听力/' 注意路径结尾要有斜杠name = 'Python剑雅'for i in range(10):isExists = os.path.exists(path + name + str(i))if not isExists:os.makedirs(path + name + str(i))print(f'{name}{str(i)} created')
7. 打包多个文件为一个可执行文件
使用PyInstaller
pyinstaller --onefile --add-data "data.txt;.data" --add-data "other_file.py;.other_file" main.py
以上方法可以帮助你在Python中处理多个文件的不同需求。请根据你的具体需求选择合适的方法
