用python将一个txt文件按行分成多个txt文件,并将这多个txt文件保存在指定文件夹中
时间: 2024-05-05 19:21:44 浏览: 13
可以使用Python中的文件操作和字符串处理函数来实现这个功能。以下是一个示例代码,它假定要分割的文件名为input.txt,每个输出文件包含10行数据,输出文件名为output1.txt、output2.txt等等,保存在名为output文件夹中。
```python
import os
# 读取要分割的文件
with open('input.txt', 'r') as f:
lines = f.readlines()
# 每个输出文件包含的行数
lines_per_file = 10
# 输出文件夹路径
output_folder = 'output'
# 确保输出文件夹存在
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 分割文件
for i, offset in enumerate(range(0, len(lines), lines_per_file)):
# 构造输出文件名
output_file = os.path.join(output_folder, f'output{i+1}.txt')
# 写入数据到输出文件
with open(output_file, 'w') as f:
f.writelines(lines[offset:offset+lines_per_file])
```
上述代码首先读取要分割的文件`input.txt`的所有行,然后使用每10行数据作为一个输出文件,将其写入到名为`output1.txt`、`output2.txt`等输出文件中,并将这些文件保存在名为`output`的文件夹中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)