2014-05-21 6 views
3

$$$$으로 키 값 (예 : db_host, addons_path)을 바꿔야합니다.파일의 특정 줄 쓰기 및 바꾸기

#Test.txt# 
addons_path=/bin/root 
admin_passwd = abctest 
auto_reload = False 
csv_internal_sep = , 
db_host = 90.0.0.1 

출력 텍스트 파일 :

#Test2.txt# 
admin_passwd = abctest 
auto_reload = False 
csv_internal_sep = , 
db_host = $$$$$ 

나는 새로운 오래된 파일을 대체하는 대신 특정 키의 값을 대체하고 파일에 쓰기 할

입력 텍스트 파일에는 다음이 포함 파일.

다음 함수

나에게 P

replace_with = '7777' 
key = 'db_host' 

fileref = open('/Files/replace_key/test','r+') 


line = fileref.readline() 
config = [] 
while line: 
    split_line = line.split('=') 
    if len(split_line) == 2: 
     config.append((split_line[0].strip(' \n'),split_line[1].strip(' \n'))) 

    print line 
    line = fileref.readline() 

fileref.close() 
config = dict(config) 
print config 

config.update({'db_host':replace_with}) 

p(config) 

로 pprint 수입 pprint에서 fileinput 함수 특정 키 수입의 값을 대체 정확한 출력을 제공하지만 전체 텍스트 파일에 적용 드릴 수 없습니다.

+5

'나오지 -i의/^ DB_HOST = * $/DB_HOST = $ $ $ $ $ /. 'test.txt' –

+0

또는 대안 :'나오지도 -i의 :^\ (DB_HOST | addons_path \). * $ : $ 1 = $$$$ : gm 'test.txt' – hjpotter92

답변

1

파이썬으로 다음과 같은 기능을 사용할 수있는 수행 할 경우

def replace_in_file(filename, key, new_value): 
    f = open(filename, "r") 
    lines = f.readlines() 
    f.close() 
    for i, line in enumerate(lines): 
     if line.split('=')[0].strip(' \n') == key: 
      lines[i] = key + ' = ' + new_value + '\n' 
    f = open(filename, "w") 
    f.write("".join(lines)) 
    f.close() 

replace_in_file("file.txt", 'db_host', "7777") 
0

이 UNIX 도구를 달성 훨씬 간단합니다.

bash-4.3$ cat - > test.txt 
#Test.txt# 
addons_path=/bin/root 
admin_passwd = abctest 
auto_reload = False 
csv_internal_sep = , 
db_host = 90.0.0.1 
bash-4.3$ python 
Python 2.7.6 (default, Apr 28 2014, 00:50:45) 
[GCC 4.8.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> with open("test.txt", "r") as f: 
...  pairs = (line.split("=", 1) for line in f if not line.startswith("#")) 
...  d = dict([(k.strip(), v.strip()) for (k, v) in pairs]) 
... 
>>> d["db_host"] = "$$$$" 
>>> with open("out.txt", "w") as f: 
...  f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()])) 
... 
>>> 
bash-4.3$ cat out.txt 
db_host=$$$$ 
admin_passwd=abctest 
auto_reload=False 
csv_internal_sep=, 
addons_path=/bin/rootbash-4.3$ 
  1. 파일을 읽고 그것이 dict (무시 의견)에 =에 의해 키/값 쌍을의 구문 분석 :

    그럼에도 불구하고 여기 내 솔루션입니다.

  2. 결과 사전에서 db_host 키를 변경하십시오.
  3. 키/값 구분 기호로 =을 사용하여 사전을 작성하십시오. 기능의 재사용 가능한 세트로 :

는 :

업데이트를 즐길 수

def read_config(filename): 
    with open(filename, "r") as f: 
     pairs = (line.split("=", 1) for line in f if not line.startswith("#")) 
     return dict([(k.strip(), v.strip()) for (k, v) in pairs]) 


def write_config(d, filename): 
    with open(filename, "w") as f: 
     f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()])) 
0

어떻게 이런 일에 대해?

def replace_string(s): 
    s = s.replace('db_host','$$$$') 
    return s 
with open('test.txt','r') as fo: 
    line = fo.read() # you could use strip() or split() additionally 
new_string = replace_string(line) 
관련 문제