Skip to main content
 首页 » 编程设计

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

2024年10月01日8jillzhang

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

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 语法错误、键盘中断...),原始文件将被破坏。为了安全起见,您可以写一个不同的名字,然后在确定时移动文件:

     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) 

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