这应该把这些信息放到一个新文件上,但我收到一个错误'tuple' object has no object 'write'
,所以我需要一些帮助来找出我的代码中的错误。
def codeData(filename):
file = open(filename)
outputFile = ("Project.txt", "w")
#makes file that will take information from given file and write on it
clinic = file.readline().strip() #takes the name of clinic and writes it
patientnumber = int(file.readline().strip()) #takes the amount of patients
for i in range(patientnumber):
outputFile.write("<patient>\n")
outputFile.write("<patientID>"+file.readline().strip()+"</patientID>\n")
outputFile.write("<clinic>"+clinic+"</clinic>\n")
age = int(file.readline().strip())
outputFile.write("<age>"+str(age)+"</age>\n")
outputFile.write("<gender>"+gender+"</gender>\n")
height = int(file.readline().strip())
outputFile.write("<height>"+str(height)+"</height>\n")
weight = int(file.readline().strip())
outputFile.write("<weight>"+str(weight)+"</weight>\n")
hba1 = int(file.readline().strip())
outputFile.write("<hba1>"+str(hba1)+"</hba1>\n")
cholesterol = int(file.readline().strip())
outputFile.write("<cholesterol>"+str(cholesterol)+"</cholesterol>\n")
outputFile.write("<smoker>"+smoker+"</smoker>\n")
systolic = int(file.readline().strip())
outputFile.write("<systolic>"+str(systolic)+"</systolic>\n")
diastolic = int(file.readline().strip())
outputFile.write("<diastolic>"+str(diastolic)+"</diastolic>\n")
file.close()
outputFile.close()
codeData("Project Text.txt")
以下是
中文件的内容UHIC
2
A31415
54
M
180
90
6.7
100
No
130
65
A32545
62
F
160
80
7.2
120
Yes
180
92
答案 0 :(得分:0)
有tuple
没有write
方法的错误正在发生,因为您没有打开输出文件,只需将传递给open
的参数放入括号:
outputFile = ("Project.txt", "w") # need to call open here!
但是,您应该使用with
语句打开和关闭两个文件:
with open(filename) as file, open("Project.txt", "w") as outputFile:
# the rest of your code, skipping the close calls
您有一个单独的错误,close
调用在您的循环中。使用with
使手动关闭完全不需要,因此您无需担心将呼叫放在何处。
与您当前错误无关的另一个建议:如果您正在阅读或编写结构化文件格式(如XML),则应该使用专用模块进行输入或输出。学习API要比编写自己的代码要容易得多,而且你更有可能让它正常工作。例如,手动编写XML以确保正确关闭所有标记时可能会很棘手。 (您的代码似乎无法在任何地方关闭其<patient>
代码,因此这可能适用于您!)
我认为对于XML而言,ElementTree
模块(xml.etree
)可能是标准库中需要的东西,但我从来没有真正使用它,所以我可以'说话权威。还有xml.dom.minidom
以及大量第三方模块。其他有更多实践经验的人可能能够就这些选择提供更好的建议。