我有一个包含以下内容的文件:
pid int| name varchar(20)| price float
1 |Giga. |10.99
2. |PowerGiga. |29.99
我想在“名称”列中的文件中用Mega替换Giga 并将价格列<15替换为13.99 我刚刚将用户输入给出的内容写到了文件中。它不存储任何映射。如何替换文件中的名称?
预期:
pid int| name varchar(20)| price float
1 |Mega. |13.99
2. |PowerGiga. |29.99
我已经使用python尝试了以下方法。
发生了什么事,我的整个文件内容都被删除了
import sys,re
import os
mypath="/Users/rk/Documents/code/PA1/"
db_used="CS457_PA2"
def updateTable():
if os.path.isdir(mypath+db_used):
filepath= mypath+db_used+"/"+filename+".txt"
if not os.path.isfile(filepath): #check if file not exists is true
print("!Failed to insert into table "+ filename +" because it does not exist.")
else :
Column1=List[3]
Column2=List[6]
value1=List[4]
value2=List[7]
newfile=open(filepath, "r")
for w in newfile:
list= w.split('|')
if value1 in list:
print(list)
a=1
print("yes")
newfile=open(filepath, "w")
for a in list:
if value1 in list[0:]:
newfile.write(a.replace(value1,value2))
print("check the file if its updated")
else:
print("nothing")
else :
db_used == " "
print("DB is not selected")
user_says = input().strip()
if "UPDATE" in user_says.upper():
temp=user_says.strip(";")
removespecial=re.sub("\W+", " ", temp) #removes special characters but preserves space
List=removespecial.split(" ")
filename=List[1]
updateTable()
else:
print("Debug")
我尝试了以下代码,并且对我有用。
with open(filepath, "rt") as fin:
with open(out, "wt") as fout:
for line in fin:
fout.write(line.replace(value2, value1))
os.remove(filepath)
os.rename(out,filepath)