简体   繁体   中英

Replace word in text file comma separated with word in a specific column with Python

Sorry but I am just stating Python and need some lights

I have a list like below:

$ cat server.txt
column1, column2, column3, column4, column5
server1, windows, 120, running , 1
server2, linux, 250, offline , 1
server3, centos, 60, maintenance, 0
server4, windows, 123, running, 1
server5, linux, 145, offline, 0

I need to replace the second column with other values like:

All the 1 in the column5 are replace by the word noissue an the 0 with the word issue but only the in column5 as I don't want to have the column3 impacted by the change

Many thanks

This will work if you are sure that the column to replace only contains 0 and 1.

firstline = True
with open("server.txt") as f:
    with open("output.txt", "w") as fw:
        for line in f.readlines(): # For each line in server.txt

            if firstline: # Do not process the header line
                firstline = False
                continue

            if line[-2] == "1": # -2 because -1 is the line return character
                line = line[:-2] + "noissue\n"
            else:
                line = line[:-2] + "issue\n"
            fw.write(line)

You can do something like

mapping = {'0':'issue', '1':'noissue'}
for line in sys.stdin:
  fields = line.split(',')
  if fields[4].strip() in mapping:
    fields[4] = mapping[fields[4].strip()]
  print ','.join(fields)

This will work on the standard input and write to stdout , so you'll have to call your program like

$ python program.py < server.txt > output.txt

if there's neither a "0" nor a "1" in the column, the value will not be changed. You can adapt the mapping , if you want to change other values too.

Note that this program doesn't handle the first line separately (see julinenc's posting to see how this could be done). As you have no '0' or '1' in your first line it will work with the example you've posted.

Also note the use of the strip() method, this gets rid of possible additional spaces around your "0" and "1"

You should use the csv module for this:

import csv

with open('server.txt', 'r') as infile, open('server_modified.txt','w') as outfile:
   reader = csv.reader(infile, delimiter=',')  # ',' is the default, but this shows
                                               # you how to change it in the future
   writer = csv.writer(outfile, delimiter=',')
   writer.writerow(next(reader)) # This will write the first row (your header)
                                 # directly to the output file

   for row in reader:
      if row[-1] == '1':
         row[-1] = 'noissue'

      if row[-1] == '0':
         row[-1] = 'issue'

      writer.writerow(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM