我有一组数字(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("-", "")
答案 0 :(得分:9)
你可以使用shell脚本轻松完成,而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)
答案 1 :(得分:9)
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'
作为第二个结果开。