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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19201575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:07:48  来源:igfitidea点击:

Python Read File, Look up a String and Remove Characters

pythonpython-2.7

提问by Shaji

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

我有一组数字(NDC - 药物编号),其中有一个-。我正在尝试读取文件,删除-并将数字写入新文件。对此的任何帮助将不胜感激。使用 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("-", "")

采纳答案by pts

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.

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

回答by neeagl

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.

您可以使用 shell 脚本轻松完成此操作,该脚本必须比 Python 实现更快。除非您对脚本有更多的了解,否则您应该使用 shell 脚本版本。

However, with Python it would be:

但是,使用 Python 将是:

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