在每行末尾添加逗号

2024-09-30 10:42:00 发布

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

我在一个文件夹中有几个html文件,如下所示:

<html>
Hello Guys
Wassap Guys
Bye Guys
</html>

在Python中,我想打开文件并在每行末尾添加逗号,如下所示:

<html>,
Hello Guys,
Wassap Guys,
Bye Guys,
</html>,

然后把它们排成一行,如下所示:

<html>,Hello Guys,Wassap Guys,Bye Guys,</html>,

以下是我尝试过的:

import os
for i in os.listdir():
    with open(i, "w+") as f:
        f.write(",".join(f.readlines())+",")

但是当我运行该模块时,它会删除html文件的所有内容,只留下一个逗号

我还尝试了一个朋友发给我的代码

import glob
import os
files= glob.glob("C:\\test\\*.html")
for i in files:
    with open(i,'r') as in_file:
        out_file_name = os.path.basename(i)
        with open(f"C:\\test\\{out_file_name}",'w') as out_file:
            out_file.write(','.join(in_file.readlines())+',')
    in_file.close()
    out_file.close()

Tags: 文件inimporthellooshtmlaswith
3条回答

您以写入附加模式打开了文件。因此,readlines返回一个空列表。 相反,读取文件,关闭它,然后以w模式重新打开以覆盖原始内容

with open("test.txt", "r") as f:
    content = [line.strip() for line in f.readlines()]

with open("test.txt", "w") as f:
    f.write(",\n".join(content)+",")
file_name = "test_file"
string_to_add = "added"

with open(file_name, 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]

with open(file_name, 'w') as f:
    f.writelines(file_lines) 

你可以试试这个。这将获取文件,将新行符号\n替换为,\n以获取所需内容。与Prune的答案类似,但他也将其添加到行的开头,而我的答案仅将其添加到行的结尾

import os
for i in os.listdir():
    with open(i, "r") as f:
        content = f.readlines()

    with open(i, "w") as f:
        lines = []
        for line in content:
            new_line = line.replace("\n","") + ",\n"
            lines.append(new_line)
        f.write("".join(lines))

相关问题 更多 >

    热门问题