【问题标题】:Add comma at end of each line在每行末尾添加逗号
【发布时间】:2021-02-28 18:04:17
【问题描述】:

我在一个文件夹中有几个 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()

【问题讨论】:

    标签: python html file text


    【解决方案1】:

    您以写入附加模式打开了文件。因此,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)+",")
    

    【讨论】:

    • 给我错误:期望一个缩进块
    • 发布的代码在 Python 3.8.2 中不会产生该错误;你必须发布你在做什么。
    【解决方案2】:

    你可以试试这个。这将获取文件,将新行符号 \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))
    

    【讨论】:

    • 我还添加了 encoding="utf8",但我不想用 ",\n" 替换 "\n"。我想把它们排成一行。 Find"[\n\r]+" 替换为 "," 在 Notepad++ 上有效,但在 python 中无效
    • 我不明白@Michael
    【解决方案3】:
    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) 
    

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 2020-02-24
      • 2015-02-16
      • 2013-04-05
      相关资源
      最近更新 更多