write to txt file one line - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: write to txt file one line (/thread-20522.html) |
write to txt file one line - antmar904 - Aug-15-2019 Hi, I have a txt file that contains 100 ip addresses with one on each line. Exp of txt file: 1.1.1.1 12.43.123.123 154.4.1.1 3.3.3.3 I need to read these ip address then write a string plus the ip address to a one line string. Exp of output txt file with "ip from txt file" would be the ip from the txt file read. "sourceIP = '1.1.1.1' or destinationIP = '1.1.1.1' or sourceIP = '12.43.123.123' or destinationIP = '12.43.123.123'" RE: write to txt file one line - Axel_Erfurt - Aug-15-2019 change "/tmp/mylist.txt" to what you need result = [] inputstring = """1.1.1.1 12.43.123.123 154.4.1.1 3.3.3.3""" for line in inputstring.splitlines(): result.append("%s %s" % ("sourceIP =", "'{}'".format(line))) output = '\n'.join(result) print(output) with open("/tmp/mylist.txt", 'w') as outfile: outfile.write(output)
RE: write to txt file one line - antmar904 - Aug-16-2019 Hi thank you for your help. The string I am looking for the output.txt file is: 'sourceIP = '1.1.1.1' or destinationIP = '1.1.1.1' or sourceIP = '12.43.123.123' or destinationIP = '12.43.123.123' and so on and so on. This seems to be working for me. Any suggestions on how to improve this code? Thanks again! filehandle = open("C:\Temp\S2S.txt", 'r') ips = filehandle.read() filehandle.close() x = "" for i in ips.split('\n'): x += "sourceIP = '" + i + "' or destinationIP = '" + i + "' " + "or " writehandle = open("C:\Temp\output2.txt", 'w') writehandle.write(x) writehandle.close() RE: write to txt file one line - Axel_Erfurt - Aug-16-2019 Then you get "or" on the end of the line. you can remove it after splitlines x = "" for i in ips.splitlines(): x += "%s %s %s %s %s" % ("sourceIP =", "'{}'".format(i), "or destinationIP =", "'{}'".format(i), "or") k = x.rfind("or") x = x[:k] + "" + x[k+2:] |