将一个文件夹中的txt文件合并
时间: 2024-02-25 13:55:54 浏览: 19
你可以使用Python来将一个文件夹中的所有txt文件合并成一个文件。以下是一个示例代码:
```python
import os
# 指定文件夹路径
folder_path = "./my_folder/"
# 获取文件夹中所有txt文件的路径
txt_files = [os.path.join(folder_path, file) for file in os.listdir(folder_path) if file.endswith(".txt")]
# 将所有txt文件合并成一个文件
with open("merged.txt", "w") as outfile:
for txt_file in txt_files:
with open(txt_file, "r") as infile:
outfile.write(infile.read())
```
这段代码将指定文件夹`"./my_folder/"`中的所有txt文件合并成一个文件`"merged.txt"`。你可以根据需要修改文件夹路径和合并后的文件名。
相关问题
将一个文件夹中的txt文件合并保存在同一个文件夹中
以下是一个示例代码,可以将指定文件夹中的所有txt文件合并并保存在同一个文件夹中:
```python
import os
# 指定原始文件夹和目标文件
source_folder = './my_folder/'
target_file = 'merged.txt'
# 获取所有txt文件的路径
txt_files = [os.path.join(source_folder, file) for file in os.listdir(source_folder) if file.endswith('.txt')]
# 合并文件内容
with open(target_file, 'w', encoding='utf-8') as target:
for file in txt_files:
with open(file, 'r', encoding='utf-8') as f:
target.write(f.read())
print('合并完成!')
```
在这个例子中,我们使用了`os.listdir()`函数获取指定文件夹中的所有文件,然后使用列表推导式筛选出所有txt文件,并将它们的路径存储在`txt_files`列表中。接着,我们打开目标文件,将每个txt文件的内容写入该文件中。最后,我们打印一条消息以提醒用户合并操作已完成。
将一个文件夹中的txt文件左右合并并输出为一个txt
您可以使用Python编写一个脚本来实现将一个文件夹中的txt文件左右合并并输出为一个txt的操作。
以下是一个示例代码:
```python
import os
folder_path = "your_folder_path"
output_file = "output.txt"
with open(output_file, "w") as output:
for file_name in os.listdir(folder_path):
# 只处理txt文件
if file_name.endswith(".txt"):
file_path = os.path.join(folder_path, file_name)
with open(file_path, "r") as f:
output.write(f.read() + " ")
output.write("\n")
```
您需要将 `your_folder_path` 替换为您要处理的文件夹路径,并将 `output.txt` 替换为您要输出的文件名。运行脚本后,所有的txt文件将被合并到一起,并输出为一个txt文件。