我在一个文件夹中有几个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
模式重新打开以覆盖原始内容你可以试试这个。这将获取文件,将新行符号
\n
替换为,\n
以获取所需内容。与Prune的答案类似,但他也将其添加到行的开头,而我的答案仅将其添加到行的结尾相关问题 更多 >
编程相关推荐