将选定的行从不同目录中的文件复制到另一个文件 [英] Copying selected lines from files in different directories to another file

查看:253
本文介绍了将选定的行从不同目录中的文件复制到另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多子目录的目录,其中包含文件。我想在 App_integrations文件夹中打开以 root.vrpj或 root.vprj结尾的文件,并将包含 table一词的行复制到另一个文件。

I have a directory with many subdirectories, containing files. I want to open the files ending with "root.vrpj" or "root.vprj", in "App_integrations" folder and copy the lines containing the word "table" to another file.

直到现在,我已经设法使用以下代码访问每个文件:

Until now I've managed to visit each file with this code:

for root, dirs, files in os.walk(movedir):
for filename in files:
    if filename.endswith(("root.vrpj", "root.vprj")):

问题是我现在拥有的只是我要访问的文件的名称,我被卡在这里。

The problem is that what I have now are just the names of the files I want to visit and I'm stuck here.

推荐答案

我终于解决了

    import os

rootdir = my root folder

# creates a file f that contains all the lines of the files 
# with "root.vrpj" or "root.vprj" in their name
# and who are inside "App_integrations" folders
# without duplicates

#creating the big file with all the file containing the lines I need
f = open('final_file.txt', 'a')
for root, dirs, files in os.walk(rootdir):  
    for filename in files:
        if (filename.endswith(("root.vrpj", "root.vprj")) and ("App_Integration" in os.path.join(root, filename))):
            full_name = os.path.join(root, filename) 
            data = open(full_name).read()
            f.write(data + "\n")                 
f.close()

#copying the lines I need to f1 without duplicates
lines_seen = set()
f = open('final_file.txt')
f1 = open('testread1.txt', 'a')
doIHaveToCopyTheLine=False
for line in f.readlines():
    if (("Table" in line) and (line not in lines_seen)):
        doIHaveToCopyTheLine=True
        if doIHaveToCopyTheLine:
            f1.write(line)
            lines_seen.add(line)
f1.close()
f.close()

这篇关于将选定的行从不同目录中的文件复制到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆