我无法写入文本文件。我的功能看起来像这样。该文件已创建,但是在运行代码后,该文件仍为空。我无法找出问题所在。
def compare(prjCode, prjName, stCode, stName, dCode, dName, sdCode, sdName):
with open('C:\\Users\\NCOG1\\Desktop\\test.txt', 'w') as f:
percentMatch = 0
sdLen = len(sdName)
prjLen = len(prjName)
if (sdLen > prjLen):
if ((sdName.find(prjName) != -1)):
res = sdName.index(prjName)
percentMatch = (prjLen/sdLen)*100
#print(prjCode,prjName,sdCode,sdName,str(round(percentMatch)),stCode, stName, dCode, dName)
#print(prjCode + "," + prjName + "," + sdCode + "," + sdName + str(round(percentMatch)) + "," + stCode + "," + dCode + "," + sdCode)
f.write(prjCode + "," + prjName + "," + sdCode + "," + sdName + "," + str(round(percentMatch)) + "," + stCode + "," + stName + "," + dCode + "," + dName + "%\n")
else:
res = 0
#print(res)
elif (prjLen >= sdLen):
if ((prjName.find(sdName) != -1)):
res = prjName.index(sdName)
percentMatch = (sdLen/prjLen)*100
#print(prjCode,prjName,sdCode,sdName,str(round(percentMatch)),stCode, stName, dCode, dName)
#print(prjCode + "," + prjCode + "," + sdCode + "," + sdName + str(round(percentMatch) + "," stCode + "," + dCode + "," + sdCode)
f.write(prjCode + "," + prjName + "," + sdCode + "," + sdName + "," + str(round(percentMatch)) + "," + stCode + "," + stName + "," + dCode + "," + dName + "%\n")
else:
res = 0
#print(res)
f.close()
答案 0 :(得分:1)
1。要在文件中写入内容,您需要将文本或int转换为String,而您没有这样做,这是主要问题
2。您键入其的路径未呈现,因为它未标识为字符串,因此您需要将路径转换为原始字符串,因为您需要在我更正的路径开始之前添加“ r”代码。
3。例如,我为虚假数据调用函数compare(),现在检查以下代码并尝试运行,让我知道是否有任何疑问。
def compare(prjCode, prjName, stCode, stName, dCode, dName, sdCode, sdName):
with open(r'C:\\Users\\NCOG1\\Desktop\\test.txt', 'w') as f:
percentMatch = 0
sdLen = len(sdName)
prjLen = len(prjName)
if (sdLen > prjLen):
if ((sdName.find(prjName) != -1)):
res = sdName.index(prjName)
percentMatch = (prjLen/sdLen)*100
#print(prjCode,prjName,sdCode,sdName,str(round(percentMatch)),stCode, stName, dCode, dName)
#print(prjCode + "," + prjName + "," + sdCode + "," + sdName + str(round(percentMatch)) + "," + stCode + "," + dCode + "," + sdCode)
f.write(str(prjCode) + "," + prjName + "," + str(sdCode) + "," + sdName + "," + str(round(percentMatch)) + "," + str(stCode) + "," + stName + "," + str(dCode) + "," + str(dName) + "%\n")
else:
res = 0
#print(res)
elif (prjLen >= sdLen):
if ((prjName.find(sdName) != -1)):
res = prjName.index(sdName)
percentMatch = (sdLen/prjLen)*100
#print(prjCode,prjName,sdCode,sdName,str(round(percentMatch)),stCode, stName, dCode, dName)
#print(prjCode + "," + prjCode + "," + sdCode + "," + sdName + str(round(percentMatch) + "," stCode + "," + dCode + "," + sdCode)
f.write(str(prjCode) + "," + prjName + "," + str(sdCode) + "," + sdName + "," + str(round(percentMatch)) + "," + str(stCode) + "," + stName + "," + str(dCode) + "," + str(dName) + "%\n")
else:
res = 0
#print(res)
compare(1,"harsh",0,"fff",34,32,78,"hharshbhut")