【问题标题】:Filter Directory using Regex and output filtered files to another directory使用正则表达式过滤目录并将过滤后的文件输出到另一个目录
【发布时间】:2019-06-07 16:10:16
【问题描述】:

我只是想创建一个运行特定目录中所有 .sql 文件的 python 3 程序,然后应用我添加的正则表达式;在某个实例之后,将对文件所做的更改写入一个单独的目录,它们各自的文件名相同。

所以,如果我在“/home/files”目录中有file1.sql和file2.sql,在我运行程序后,输出应该将这两个文件写入“/home/new_files”而不改变文件的内容原始文件。

这是我的代码:

import glob
import re
folder_path = "/home/files/d_d"
file_pattern = "/*sql"
folder_contents = glob.glob(folder_path + file_pattern)


for file in folder_contents:
    print("Checking", file)
for file in folder_contents:
    read_file = open(file, 'rt',encoding='latin-1').read()
    #words=read_file.split()
    with open(read_file,"w") as output:
        output.write(re.sub(r'(TBLPROPERTIES \(.*?\))', r'\1;', f, flags=re.DOTALL))

我收到文件名太长的错误:“CREATE EXTERNAL TABLEe”,而且我不太确定将输出路径 (/home/files/new_dd) 放在代码中的什么位置。

有什么想法或建议吗?

【问题讨论】:

  • 只需运行我的目录并通过添加正则表达式元素对其进行过滤,然后保存文件。
  • 有什么不明白的?
  • 你能不能举个folder_contents的例子,也许是一个包含该变量内容的列表

标签: python regex python-3.x glob os.path


【解决方案1】:

使用read_file = open(file, 'rt',encoding='latin-1').read(),文件的全部内容被用作文件描述符。此处提供的代码迭代使用 glob.glob 模式打开以读取、处理数据和打开以写入的文件名(假设文件夹 newfile_sqls 已经存在, 如果不是,则会出现错误FileNotFoundError: [Errno 2] No such file or directory)。

import glob
import os
import re

folder_path = "original_sqls"
#original_sqls\file1.sql, original_sqls\file2.sql, original_sqls\file3.sql
file_pattern = "*sql"
# new/modified files folder
output_path = "newfile_sqls"

folder_contents = glob.glob(os.path.join(folder_path,file_pattern))

# iterate over file names
for file_ in [os.path.basename(f) for f in folder_contents]:

    # open to read
    with open(os.path.join(folder_path,file_), "r") as inputf:
        read_file = inputf.read()

    # use variable 'read_file' here
    tmp = re.sub(r'(TBLPROPERTIES \(.*?\))', r'\1;', read_file, flags=re.DOTALL)

    # open to write to (previouly created) new folder
    with open(os.path.join(output_path,file_), "w") as output:
        output.writelines(tmp)

【讨论】:

    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多