我在一个文件夹中有几个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)+",")
你可以试试这个。这得到文件,用,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))
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)