Я пытаюсь изменить строку на переменную.
В основном я пытаюсь распространить файл '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()
Если вы любезно добавите какое-нибудь объяснение, которое будет мне благодарно.
Заранее спасибо.