我在一个文件夹中有几个 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()
答案 0 :(得分:2)
您以写入附加模式打开文件。因此,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)+",")
答案 1 :(得分:0)
newSheet.getRange(2,1,data.length,17).setValues(data);
newSheet.getRange(2,10,sheetBG.length,sheetBG[0].length).setBackgrounds(sheetBG); // new code
答案 2 :(得分:0)
你可以试试这个。这将获取文件,将新行符号 \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))