将字符串替换为变量后将文件分发(复制)到数字目录-python3.x

时间:2019-05-19 17:00:25

标签: python-3.x file automation

我正在尝试将字符串更改为变量。

基本上,我正在尝试将'trash.sh'文件分发到数字目录(位于目录中的目录),并用列表替换某些字符串。     (变量位于两个路径(~/pa/th)和最后一个路径(~/path)的末尾 因此,(target_1 to ~/pa/th)(target_2 to ~/path)

我知道var不能放在var.replace()中,但是我找不到其他方法来做同样的事情。

import os
import shutil
import sys

###################################################################
# Functions
def get_rank(xyz):                                       # Define a variable
    pref = xyz.split('-')[1]                         # Split at '-' and select the arg after -
    pref = pref.replace('.xyz', '')                  # Replace '.xyz' to ''  (000.xyz to 000)
    return pref                              # Ends the execution of the function call and 'returns' the result

def get_files(path, ext):                # Define a variable files = [ x for x in os.listdir(path) if ext in x ]     # 'x' is in the list of directory on the 'path' and has the 'ext' which is the variable, 'files'
    files = [ (path + x) for x in files ]                # The 'x' in the 'files' will be add to the 'path' so the 'files' is defined as 'path/file.ext'
    return files                         # So, 'files' = has 'ext' and exist in the 'path'. Moreover, it's 'path' + 'x'

def get_directories(path):
    directories = [ x for x in os.listdir(path)]     # 'directories' = x which is in the 'path'
    directories = [ (path + x) for x in directories]     # now directories = x that x is x + path
    return directories          

# copy and paste the essential files to the same directories where .xyz located    
_dir = get_directories(dest)                     # dir = /Users/tonggihkang/Desktop/scott/ranked/023 ...

file_1 = 'control.in'
file_2 = 'gtof.sh'
file_3 = 'trash_1.sh'

for j in range(len(_dir)):

    shutil.copy(root + file_1, _dir[j])          # copy the 'control.in' to the directory (~/001 002 003...)
    shutil.copy(root + file_2, _dir[j])          # copy the 'gtof.sh' to the directory (~/001 002 003...)
    shutil.copy(root + file_3, _dir[j])    
    print('copy "gtof.sh", "control.in", "trash_1.sh" in 0' + str (j+1) + ' Done\n')




## Produce and copy "trash.sh" to directories with right contents ##



root = '/Users/tg/Desktop/sc/'
path = '/Users/tg/Desktop/sc/top_structures/'
dest = '/Users/tg/Desktop/sc/ranked/'

dir_1 = [ (x.replace(root, '')) for  x in _dir ]     # dir_1 = ranked/001 ranked/002... 
dir_2 = [ (x.replace(dest, '')) for  x in _dir ]         # dir_1 = 001 002... 

foo = 'trash_1.sh'
bar = 'trash.sh'

boo = 'target_1'
far = 'target_2'

for i in range(len(_dir)):
    if i == 1:
    break

    contents = []

    with open(_dir[i] + '/' +  foo, 'r') as tmp:
    with open(_dir[i] + '/' + bar, 'r') as sourcef: 
        for line in sourcef:
        tmp.write(line.replace('target_1', dir_1).replace('target_2', dir_2))
    sourcef.close()
    tmp.close()

如果您能补充一些解释,请多多关照。

先谢谢您

0 个答案:

没有答案