Python读取文件,查找字符串并删除字符 [英] Python Read File, Look up a String and Remove Characters
本文介绍了Python读取文件,查找字符串并删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组数字(NDC - 药物编号),其中包含 -
.我正在尝试读取文件,删除 -
并将数字写入新文件.对此的任何帮助将不胜感激.使用 Py 2.7
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("-", "")
推荐答案
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'
之间),以二进制模式打开这两个文件: pass 'rb'
或 'wb'
作为 open 的第二个参数.
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.
这篇关于Python读取文件,查找字符串并删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文