【发布时间】: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()
【问题讨论】: