如何使用python在单个文件中附加多个文件上下文和文件路径

2024-09-30 06:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在路径/opt/data/file1.txt file2.txtfile3.txt中有多个文件

我想在单个文件中附加所有上下文,如路径/opt/alltxt.txt 文件内容,如

path /opt/data/file1.txt
"file1 context"    

path /opt/data/file2.txt
"file2 context"

path /opt/data/file2.txt
"file2 context"

Tags: 文件path路径txt内容datacontextfile1
1条回答
网友
1楼 · 发布于 2024-09-30 06:11:07

请尝试以下代码。也许对你有帮助

import os
import glob
def remove_newlines(fname):
    flist = open(fname).readlines()
    return [s.rstrip('\n') for s in flist]

my_file=open("all_content_file.txt", "w")
for i in glob.glob('./*.txt'):
    my_file.write("path")
    my_file.write(os.path.abspath(i))
    my_file.write(" ")
    for j in remove_newlines(os.path.abspath(i)):
        my_file.write(j)
        my_file.write(" ")
    my_file.write("\n")

相关问题 更多 >

    热门问题