2015-11-25 35 views
-1

使用Python,如果我想Python的argv的文件,编辑,然后写入新文件

A.读取文本文件中使用的argv
B.使字符串替换(搜索&替换)
C.写用新名称创建一个新文件

我可以使用一个open()函数吗?这就是我到目前为止,是的,我知道它不会按原样运行。

import sys, re 

FarmFixer, farmfile = argv 

print "What is the serial number of the site?", 
_nnn = raw_input() 

print "What is the brand, or product name?", 
_brand = raw_input() 

print "What is the (fqdn) ServerName?", 
_server_name = raw_input() 

print "What is the content path?", 
_content_path = raw_input() 

print "What is the DAM path?", 
_dampath = raw_input() 

print "Which environment is this for?", 
_env = raw_input() 

print "What is the cache document root?", 
_cache_docroot = raw_input() 

for line in file_open: 
    re.sub("NNN", "_nnn", line) 
    re.sub("BRAND", "_brand", line) 
    re.sub("CONTENT_PATH", "_content_path", line) 
    re.sub("DAMPATH", "_dampath", line) 
    re.sub("ENV", "_env", line) 
    re.sub("CACHE_DOCROOT", "_cache_docroot", line) 

farmfile = _nnn + _brand + "farm.any" 
outie = open(farmfile, 'w') 
outie.close 
print farmfile 

当然re.sub行失败了。

+0

现在不要介意破损的re.sub行。 –

+0

建议:使用'with'语句来处理关闭文件。发生错误更安全,编码更简单。您发布的代码不会调用close方法。 – dsh

+0

'outie.close'不关闭文件。 'outie.close()'确实。 –

回答

2

你说你有两个文件,一个你会阅读,一个你想写的新文件。您需要打开每个文件。

这个问题与以前的问题基本相同:edit text file using Python。您需要打开一个文件,读取它,打开另一个文件并写入。

+0

是的,那是我。我仍然没有学到太多的Python。 谢谢。 –

+0

@dsh,你是怎么知道OP在6年前考虑过这个问题的? –

+0

@PadraicCunningham当我今天看到第二个“farmfile”问题时,我在回复之前检查了他的个人资料,以便我能够制定出适当的回应。这个问题位居榜首,因为这是他投票最多的问题,也是他金牌的来源。然后我保留了这个答案,因为这个答案已经有了更详细的解释和例子。 – dsh