如何将多个文本文件内容重写为同一文件中的列表?

How to rewrite multiple text files contents to lists in same file?

我有多个文本文件,其中包含两到三行文本。我需要重写这些文件以便在其中包含列表以使数据结构化。我找不到使用多个文件自动执行任务来解决它的方法。

import sys
import glob

path = '*.txt'   
files = glob.glob(path)

contents = []   
for name in files:
     with open(name) as f:
       lines = f.read().splitlines()
       contents.append(lines)

之前的文本:

Announcement
45 789 answers
Rules obliged

改写后的文字:

Announcement, 45 789 answers,Rules obliged

最终工作代码

import glob

   path = '*.txt'   
   files = glob.glob(path)

   contents = []   

   for name in files:
         # no change made to your reading code
         with open(name) as f:
           lines = f.read().splitlines()
         # overwrite the original files, put the text in one line, separated by 
         #comma+space
         with open(name,"w") as f:
         f.write(", ".join(lines))
         f.write("\n")  # add optional linefeed for the sole line

您可以使用合并版本的文件行覆盖您的文件:

for name in files:
     # no change made to your reading code
     with open(name) as f:
       lines = f.read().splitlines()
     # overwrite the original files, put the text in one line, separated by comma+space
     with open(name,"w") as f:
       f.write(", ".join(lines))
       f.write("\n")  # add optional linefeed for the sole line

注意它产生:

Announcement, 45 789 answers, Rules obliged

没有

Announcement, 45 789 answers,Rules obliged

另请注意,如果回写文件时出现任何问题(磁盘已满,python语法错误,键盘中断...),原始文件将被破坏。为了安全起见,你可以写一个不同的名字,然后在OK时移动文件:

     with open(name+".bak","w") as f:
       f.write(", ".join(lines))
       f.write("\n")  # add optional linefeed for the sole line
     shutil.move(name+".bak",name)

因为两个文件都在同一个文件系统上,所以没有性能问题(删除+重命名)