Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import fileinput, sys
- for line in fileinput.input(["test.txt"], inplace=True):
- line = line.replace("car", "truck")
- # sys.stdout is redirected to the file
- sys.stdout.write(line)
- filename = "/etc/ipf.conf"
- text = open(filename).read()
- open(filename, "w").write(text.replace(LASTKNOWN, CURRENT))
- from __future__ import with_statement
- from contextlib import nested
- in_filename, outfilename = "/etc/ipf.conf", "/tmp/ipf.conf"
- with nested(open(in_filename), open(outfilename, "w")) as in_, out:
- for line in in_:
- out.write(line.replace(LASTKNOWN, CURRENT))
- os.rename(outfilename, in_filename)
- f = open(filename, "r")
- lines = f.readlines()
- # Assume that change_ip is a function that takes a string and returns a new one with the ip changed): example below
- ret_lines = [change_ip(lines) for line in lines]
- new_file = open(new_filename, "w")
- new_file.writelines(lines)
- def change_ip(str):
- ''' Gets a string, returns a new string where the ip is changed '''
- # Add implementation, something like: return str.replace(old_ip, new_ip) or something similair.
- Simply a test file 175.48.204.168
- And two times 175.48.204.168 on this line 175.48.204.168
- Done.
- Simply a test file 10.73.144.112
- And two times 10.73.144.112 on this line 10.73.144.112
- Done.
- import socket
- import fileinput
- import subprocess
- import string
- import re
- CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
- LASTKNOWN = '175.48.204.168'
- if CURRENT == LASTKNOWN:
- print 'Nevermind.'
- subprocess.sys.exit()
- else:
- cf = open("/tmp/iiiipf.conf", "r")
- lns = cf.readlines()
- # close it so that we can open for writing later
- cf.close()
- # assumes LASTKNOWN and CURRENT are strings with dotted notation IP addresses
- lns = "".join(lns)
- lns = re.sub(LASTKNOWN, CURRENT, lns) # This replaces all occurences of LASTKNOWN with CURRENT
- cf = open("/tmp/iiiipf.conf", "w")
- cf.write(lns)
- cf.close()
- import in_place
- with in_place.InPlace('data.txt') as file:
- for line in file:
- line = line.replace('test', 'testZ')
- file.write(line)
Add Comment
Please, Sign In to add comment