Python读取文件,查找字符串并删除字符

Sha*_*aji 4 python python-2.7

我有一组数字(NDC - 药物编号),其中包含一个-.我正在尝试读取文件,删除-并将数字写入新文件.任何帮助都将不胜感激.使用Py 2.7

1. 68817-0134-50
2. 68817-0134-50
3. 68817-0134-50
Run Code Online (Sandbox Code Playgroud)

问题是连字符并不总是处于相同的位置.

1. 8290-033010
Run Code Online (Sandbox Code Playgroud)

它会发生变化,可以处于任何位置

with open('c:\NDCHypen.txt', 'r') as infile,
     open('c:\NDCOnly.txt', 'w') as outfile:
    replace("-", "")
Run Code Online (Sandbox Code Playgroud)

pts*_*pts 11

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)
Run Code Online (Sandbox Code Playgroud)

为了防止行结尾的转换(例如在'\r\n'和之间\n'),以二进制模式打开两个文件:pass 'rb''wb'作为open的第二个arg .


小智 9

你可以使用shell脚本轻松地完成它,它必须比python实现更快.除非你有更多的脚本,你应该使用shell脚本版本.

但是,使用Python它将是:

with open('c:\NDCHypen.txt', 'r') as infile, open('c:\NDCOnly.txt', 'w') as outfile:
    temp = infile.read().replace("-", "")
    outfile.write(temp)
Run Code Online (Sandbox Code Playgroud)