Python Read File, Look up a String and Remove Characters

后端 未结 2 963
我寻月下人不归
我寻月下人不归 2020-12-10 19:40

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.

相关标签:
2条回答
  • 2020-12-10 19:59
    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.

    0 讨论(0)
  • 2020-12-10 20:15

    You can do it easily with a shell script which would be must faster than a python implementation. Unless you have something more with the script, you should go with the shell script version.

    However, with Python it would be:

    with open('c:\NDCHypen.txt', 'r') as infile, open('c:\NDCOnly.txt', 'w') as outfile:
        temp = infile.read().replace("-", "")
        outfile.write(temp)
    
    0 讨论(0)
提交回复
热议问题