Python用多个文件中的随机数字替换字符串

时间:2017-06-14 18:01:17

标签: python python-2.7 python-3.x

此代码从目录中读取文件,并将字符串“400432”替换为python生成的随机6位数字,构建脚本并执行。

每个文件都应该有一个唯一的随机6位数字和相应的脚本。文件1:123456和脚本123456.sh,文件2:775463和脚本775463.sh等。

问题是当存在多个文件时,123456将写入所有文件,并且仅创建123456.sh。我不知道如何循环这个,因为我使用了python已经3年了。

努力完成这项任务。谢谢你的帮助!

#!/usr/bin/python

import os
import stat
import fileinput
import glob
import sys
import re
import random
import subprocess
import string


##############################################################
# Generates random numbers and replaces in WSP files
##############################################################

def random_digits(y):
    return ''.join(random.choice(string.digits) for x in range(y))
rand = str(random_digits(6))
_replace_re = re.compile("400432")
for dirpath, dirnames, filenames in os.walk("/home/mark/WSP_IN/"):
    for file in filenames:
        file = os.path.join(dirpath, file)
        head, tail = os.path.split(file)
    tempfile = file + ".temp"
        with open(tempfile, "w") as target:
            with open(file) as source:
                for line in source:
                    line = _replace_re.sub(rand, line)
                    target.write(line)
            os.rename(tempfile, file)
##############################################################
# Creates script that builds ship to based on random numbers
##############################################################

s = open('/usr/local/bin/wsp_scripts/' + rand + '.sh', 'wb+')

##############################################################
# Define responses as string arguments rather than text
##############################################################

data = '/usr/local/bin/wsp_scripts/'
ext = '.sh'
space = ' ';
script = 'exec ${B}/pro5 -c${CF}'
pathx = ' -m2048 -q ${P} - '
swfile = str(tail+space)
swship = str(rand)
sscript = str(script)
spathx = str(pathx)
shell = str(data+rand+ext)

##############################################################
# Write static text and arguments into file
##############################################################

s.write('#!/bin/bash' + '\n')
s.write('#termsoa=/soatermsystem' + '\n'),
s.write('PATH=$PATH:/usr/basic:/usr/basic/util' + '\n')
s.write('B=/usr/local/basis/pro5' + '\n')
s.write('P=/usr5/prog/utils/SO/EDIshipbuild' + '\n')
s.write('CF=/usr/local/basis/pro5/config.bbx'+ '\n')
s.write('TERMCAP=${B}/termcap' + '\n')
s.write('export PATH TERM TERMCAP' + '\n')
s.write('umask 0' + '\n')
s.write('cd /usr/basic' + '\n')
s.write(sscript+spathx+swfile+rand)

st = os.stat(shell)
os.chmod(shell, st.st_mode | stat.S_IEXEC)
s.close()

##############################################################
# Import script just created and execute
##############################################################

cmd = '/usr/local/bin/wsp_scripts/' + rand + '.sh'

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
result = out.split('\n')
for lin in result:
   if not lin.startswith('#'):
       print(lin)
s.close()

2 个答案:

答案 0 :(得分:0)

您定义rand并在for循环之外创建.sh文件。如果要为每个文件重新定义rand,请将其定义移动到内部for循环中。同样适用于.sh文件创建。

我认为这看起来像这样。

def random_digits(y):
    return ''.join(random.choice(string.digits) for x in range(y))

_replace_re = re.compile("400432")

for dirpath, dirnames, filenames in os.walk("/home/mark/WSP_IN/"):
    for file in filenames:
        rand = str(random_digits(6))
        file = os.path.join(dirpath, file)
        head, tail = os.path.split(file)
        tempfile = file + ".temp"
        with open(tempfile, "w") as target:
            with open(file) as source:
                for line in source:
                    line = _replace_re.sub(rand, line)
                    target.write(line)
        os.rename(tempfile, file)
        ##############################################################
        # Creates script that builds ship to based on random numbers
        ##############################################################

        s = open('/usr/local/bin/wsp_scripts/' + rand + '.sh', 'wb+')

答案 1 :(得分:0)

我不知道,如果要求使用6位数?

SELECT SUM ([CS_EQ_SHPD]) as CS_EQ_SHPD
FROM  [Supplies_DB].DBO.[ITEM] 
LEFT JOIN [Supplies_DB].DBO.[BU] 
ON BU_# = Business_Unit
WHERE FISC_WEEK = '49' AND FY17_Market = 'Southeast'

它将返回10位数的时间戳,并且始终是唯一的。

如果有帮助,请告诉我!