繁体   English   中英

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

[英]Python Read File, Look up a String and Remove Characters

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

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

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

1. 8290-033010

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

with open('c:\NDCHypen.txt', 'r') as infile,
     open('c:\NDCOnly.txt', 'w') as outfile:
    replace("-", "")
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)

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

你可以使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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