修改文件的简单脚本

有的时候需要有规律的修改一个文件,这个脚本还是很有用的。

import os
from tempfile import mkstemp
from shutil import move
from os import remove


def replace(source_file_path, change):
    fh, target_file_path = mkstemp()
    with open(target_file_path, 'w', encoding='utf-8') as target_file:
        with open(source_file_path, 'r', encoding='utf-8') as source_file:
            for line in source_file:
                target_file.write(change(line))
    remove(source_file_path)
    move(target_file_path, source_file_path)


def change_package(line):
    key = 'package com.google.zxing.client'
    if line.startswith(key) and line != (key + ';'):
        subFix = line[len(key):]
        if (not subFix.startswith(';')) and (not subFix.startswith('.')):
            dd = key + '.' + subFix
            print(dd)
            line = dd
    return line


def travel_folder(folder_name, change):
    for x in os.walk(folder_name):
        path = x[0]
        for item in x[2]:
            replace(str(path) + "/" + str(item), change)


def change_keys(line):
    items = line.split(',')
    new_items = []
    new_items.append(items[1])
    new_items.append(items[2])
    new_items.append(items[2])
    new_items.append(items[3])
    return ','.join(new_items) + "\n"


if __name__ == '__main__':
    path = '/Users/taoli/Downloads/ep_wallet_priv.csv'
    replace(path, change_keys)
    # path = 'your folder'
    # travel_folder(path, change_package)

  • 遍历文件夹使用travel_folder方法,处理单个文件使用replace方法
  • 需要传入一个处理一行的方法,比如这里的change_keyschange_package

你可能感兴趣的:(修改文件的简单脚本)