2015-11-25 34 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