Python脚本将相同的命令应用于文件夹中的每个文件

时间:2016-01-07 04:11:40

标签: python regex

理想情况下,我想创建一个Python脚本,将相同的RegEx命令应用于特定文件夹中的所有单个文件 - 此脚本会将命令应用于输入文件,然后将文件保存到同一文件夹,不同的扩展名(即.txt而不是.tt)。

让我们说我有一个有5个不同文件的文件夹:

FOLDER1
    File1.tt
    File2.tt
    File3.tt
    File4.tt
    File5.tt

我想使用以下命令将.tt文件转换为.txt文件

awk '{print $1"_"$2}' < File1.tt | tr -s "\n" " " > File1.txt 

但是,我不想将此命令单独应用于每个文件。相反,我想创建一个Python脚本,允许我将此命令应用于文件夹中的每个文件。

2 个答案:

答案 0 :(得分:0)

如何使用endswithshutilos.walk如下 - 此脚本将在文件夹.tt中找到endswith扩展名(C:\Users\fldr}的所有文件,如果不存在相应的.txt文件,则会创建相应的{{1文件并将.txt的内容复制到该文件夹​​中的.tt文件中,即.txt

C:\Users\fldr

答案 1 :(得分:0)

这是一种天真的,无痛的方法,很多代码,但可读性和可维护性。只需将此脚本放在您想要操作的目录之外。

import os

myfiles_directory = "testing"

def files_in_dir(dirname):
    """
    Given a valid directory it will do the listing of files inside that directory
    @param: dirname --> Directory where your files are residing.
    """
    if(os.path.isdir(dirname)):
        return os.listdir(dirname)


def full_filepath(filename, directory):
    """
    Given a filename and a directory, construct the full file path,
    tracking our current working directory.
    @param: filename --> File we want to make full path of.
    @param: directory --> The directory to make path against the file.
    """
    if(isinstance(filename, list)):
        for files in filename:
            yield os.path.join(os.path.join(os.getcwd(), directory), files)


def write_rename_file(fullfilepath, current_prefix="tt"):
    """
    For simplicity we shall open the file and write it with a new name
    based on the other name.
    @param: fullfilepath --> The whole file path we want to operate on.
    @param: current_prefix --> The prefix we want to get rid of, replacing with txt.
    """
    if(fullfilepath.endswith(".txt")):
        pass 
    else:
        open_current_file = open(fullfilepath, "r")
        open_new = fullfilepath[:-len(current_prefix):] + "txt"

        # Preventing creating new file again
        if(os.path.exists(open_new)):
            pass 
        else: 
            open_new_file = open(open_new, "w")
            open_new_file.write(open_current_file.read())
            open_new_file.close()
            os.remove(fullfilepath)

fileslist = files_in_dir(myfiles_directory)

for f in  full_filepath(fileslist, myfiles_directory):
    print write_rename_file(f)

我希望这对你有用,花点时间了解脚本的作用 尝试修改它并满足您的需求。 请记住,文件最终被删除