2013-05-05 65 views
-4

我需要一些东西来替换字符串的文件至极被放置在mktemp的文件夹中。这个文件被命名为autounattend.cfg并且包含一个名为%PASSWORD的字符串,这个字符串需要被args.password替换。那么如何做到这一点?Python的替换字符串中的文件

这里是我的代码:

import shutil 
from tempfile import mktemp 
import argparse 
import os 
import subprocess 
import re 

#Argumente umwandeln 
parser = argparse.ArgumentParser(description='Build ISO Image.') 
parser.add_argument('--source', '-sr', 
       action='store', 
       help='Sourcepath -sr or --source') 

parser.add_argument('--destination', '-dn', 
       action='store', 
       help='Targetpath -dn or --destination') 

parser.add_argument('--password', '-pw', 
       action='store', 
       help='Root image password -pw or --password') 

parser.add_argument('--networkmode', '-n', 
       action='store', 
       help='Networkmode -nm or --networkmode') 

parser.add_argument('--ipadress', '-ip', 
       action='store', 
       help='Ipadress -ip or --ipadress') 

parser.add_argument('--gateway', '-gw', 
       action='store', 
       help='Gateway -gw or --gateway') 

parser.add_argument('--nameserver', '-ns', 
       action='store', 
       help='Nameserver -ns or --nameserver') 

parser.add_argument('--netmask', '-nm', 
       action='store', 
       help='Netmask -nm or --netmask') 

parser.add_argument('--hostename', '-hn', 
       action='store', 
       help='Hostname -hn or --hostname') 

args = parser.parse_args() 

final_path = mktemp(prefix='tmpiso_', dir=args.destination) 
shutil.copytree(args.source, final_path) 

exit() 
+2

而你的问题/错误是什么?发布的代码有什么问题? – fgb 2013-05-05 20:45:08

+1

你应该更清楚一点,你的要求和提供更多信息 – Serial 2013-05-05 21:13:02

+0

什么都没有,但我需要一些东西来替换文件中的字符串,放在该mktemp文件夹中。这个文件被命名为autounattend.cfg并且包含一个名为%PASSWORD的字符串,这个字符串需要被args.password替换。 那么该怎么做? 请帮忙;) – vioman 2013-05-05 21:47:33

回答

1

我没有检查这一点,但:

import re 

file = open('autounattend.cfg', 'wb') 
content = file.readlines() 
content = re.sub(r'%PASSWORD', args.password, content) 
file.write(content) 
file.close() 

应该这样做。

尽管你需要在你的文件路径中。