简体   繁体   中英

Replacing value in text file column with string

I'm having a pretty simple issue. I have a dataset (small sample shown below)

22 85 203 174 9 0 362 40 0
21 87 186 165 5 0 379 32 0
30 107 405 306 25 0 756 99 0
6 5 19 6 2 0 160 9 0
21 47 168 148 7 0 352 29 0
28 38 161 114 10 3 375 40 0
27 218 1522 1328 114 0 1026 310 0
21 78 156 135 5 0 300 27 0

The first issue I needed to cover was replacing each space with a comma I did that with the following code

import fileinput

with open('Data_Sorted.txt', 'w') as f:
    for line in fileinput.input('DATA.dat'):
        line = line.split(None,8)
        f.write(','.join(line))

The result was the following

22,85,203,174,9,0,362,40,0
21,87,186,165,5,0,379,32,0
30,107,405,306,25,0,756,99,0
6,5,19,6,2,0,160,9,0
21,47,168,148,7,0,352,29,0
28,38,161,114,10,3,375,40,0
27,218,1522,1328,114,0,1026,310,0
21,78,156,135,5,0,300,27,0

My next step is to grab the values from the last column, check if they are less than 2 and replace it with the string 'nfp'.

I'm able to seperate the last column with the following

for line in open("Data_Sorted.txt"):
    columns = line.split(',')

    print columns[8]

My issue is implementing the conditional to replace the value with the string and then I'm not sure how to put the modified column back into the original dataset.

There's no need to do this in two loops through the file. Also, you can use -1 to index the last element in the line.

import fileinput

with open('Data_Sorted.txt', 'w') as f:
    for line in fileinput.input('DATA.dat'):
        # strip newline character and split on whitespace
        line = line.strip().split()

        # check condition for last element (assuming you're using ints)
        if int(line[-1]) < 2:
            line[-1] = 'nfp'

        # write out the line, but you have to add the newline back in
        f.write(','.join(line) + "\n")

Further Reading :

You need to convert columns[8] to an int and compare if it is less than 2.

for line in open("Data_Sorted.txt"):
    columns = line.split(',')
    if (int(columns[8]) < 2):
        columns[8] = "nfp"
    print columns

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