[英]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.