【问题标题】:Merging specific files of a directory in python在python中合并目录的特定文件
【发布时间】:2020-06-11 18:11:47
【问题描述】:

我有一个目录 C:/newdir/ 它包含以下文件名:

s1_student1_file
t1_teacher2_file
hab_parent5_file
y1_professor_file 
bsa_assistant2_file
t1_student_file
nas_officer_file
ee1_newguy15_file
ee1_professor15_file
f1_student8_file

我想将 s1_student1_file、t1_teacher2_file、t1_student_file、y1_professor_file、ee1_newguy15_file、f1_student8_file 和 ee1_professor15_file 的内容合并到一个名为 all_file 的新文件中,并从我拥有的目录中删除已合并的文件为此编写一个python代码,但不知道如何。

【问题讨论】:

  • 它们是文本文件吗?
  • 是的,它们是文本文件

标签: python python-3.x merge


【解决方案1】:

您可以使用glob 列出选定文件夹中所有选定的文本文件。然后,您可以使用 for 循环遍历所有文本文件并将内容写入另一个文件:

from glob import glob

with open('all_file.txt','a') as f:
    for file in glob('s1*')+glob('t1*')+glob('y1*')+glob('ee1*'):
        with open(file+'txt','r') as r:
            f.write(r.read())

之后删除文件:

from glob import glob
import os
with open('all_file.txt','a') as f:
    for file in glob('s1*')+glob('t1*')+glob('y1*')+glob('ee1*'):
        with open(file,'r') as r:
            f.write(r.read())
        os.remove(file)

【讨论】:

  • 抱歉还有一件事,我应该在代码中的哪个位置传递我的目录作为参数?
  • 你可以把glob('s1*')+glob('t1*')+glob('y1*')+glob('ee1*')改成["C:/newdir/"+file for file in glob('s1*')+glob('t1*')+glob('y1*')+glob('ee1*')]
  • 嗨,那么在将它们合并到同一代码中后,如何从目录中删除所有已合并的文件
  • 只需在上下文管理器下方添加os.remove(file+'.txt')..
  • 您好,代码正在运行,没有显示任何错误,但文件没有被删除
【解决方案2】:

导入 shutil 和 pathlib 库

您可以使用此命令安装库 -

pip install shutil

pip 安装路径库

Python 实现

import shutil 
from pathlib import Path 

firstfile = Path(r'C:\Users\Sohom\Desktop\A.txt') 
secondfile = Path(r'C:\Users\Sohom\Desktop\B.txt') 

newfile = input("Enter the name of the new file: ") 
print() 
print("The merged content of the 2 files will be in", newfile) 

with open(newfile, "wb") as wfd: 

for f in [firstfile, secondfile]: 
    with open(f, "rb") as fd: 
        shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) 

  print("\nThe content is merged successfully.!") 
 print("Do you want to view it ? (y / n): ") 

 check = input() 
 if check == 'n': 
exit() 
else: 
print() 
c = open(newfile, "r") 
print(c.read()) 
c.close()

......

动态创建文本文件数组

【讨论】:

  • Ann Zen 的代码完成了这项工作,但我很难在合并后从目录中删除必须合并的文件。你能帮我解决这个问题吗
  • import os //在循环中调用这个使用文件数组 file_path = '/tmp/file.txt' os.remove(file_path)
猜你喜欢
  • 2018-10-26
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 2016-12-17
  • 2017-02-27
  • 1970-01-01
相关资源
最近更新 更多