[英]Add comma at end of each line
我在一个文件夹中有几个 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()
您以写入附加模式打开了文件。 因此, 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.