Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Read File, Look up a String and Remove Characters

I have a set of numbers (NDC - drug numbers) that have a - in them. I am trying to read the file, remove the - and write the numbers to a new file. Any help with this would be appreciated. Using Py 2.7

1. 68817-0134-50
2. 68817-0134-50
3. 68817-0134-50

The issue is that the hyphen is not always in the same position.

1. 8290-033010

It changes and can be in any position

with open('c:\NDCHypen.txt', 'r') as infile,
     open('c:\NDCOnly.txt', 'w') as outfile:
    replace("-", "")
like image 947
Shaji Avatar asked Nov 27 '22 21:11

Shaji


1 Answers

with open(r'c:\NDCHypen.txt', 'r') as infile, \
     open(r'c:\NDCOnly.txt', 'w') as outfile:
    data = infile.read()
    data = data.replace("-", "")
    outfile.write(data)

To prevent the conversion of line endings (e.g. between '\r\n' and \n'), open both files in binary mode: pass 'rb' or 'wb' as the 2nd arg of open.

like image 86
pts Avatar answered Dec 06 '22 16:12

pts