tka3214 tka3214 - 1 month ago 6
Python Question

How to add additional variable headers to .txt file?

So I am trying to add headers to data in .txt

With the current code I have it creates headers; however, it also deletes the values correlated for each variable.

Any suggestions on how I can create a code that does not delete my values?

infile=open("Z:\\data2.txt", "r")
outfile =open("Z:\\data3.txt", "w")

count=0
for line in infile.readlines():
if count<1:
d="concord_Old_SAT_V"
e="concord_Old_SAT_M"
f="concord_Old_SAT_W"
g="concord_ACT_C"
h="concord_ACT_R"
i="concord_New_SAT_C"
j="concord_New_SAT_RW"
k="concord_New_SAT_M"
l="concord_New_SAT_R_Test"
m="concord_New_SAT_W_Test"
n="concord_New_SAT_M_Test"
outfile.write(line.strip("\n") + '\t' + d + '\t'+ e + '\t' + f + '\t' + g + '\t' + h + '\t' + i + '\t' + j+ '\t' + k + '\t' + l+ '\t' + m + '\t' + n+ "\n")
count+=1
infile.close()
outfile.close()

Answer

If your header-less data are contained in Z:\\data2.txt, then all you have to do is open the file in r+ mode, read the content and put it back after prepending your headers to the content. You may not need to make a file at all. The following should be a decent starting point:

headers = ["concord_Old_SAT_V",
  "concord_Old_SAT_M",
  "concord_Old_SAT_W",
  "concord_ACT_C",
  "concord_ACT_R",
  "concord_New_SAT_C",
  "concord_New_SAT_RW",
  "concord_New_SAT_M",
  "concord_New_SAT_R_Test",
  "concord_New_SAT_W_Test",
  "concord_New_SAT_M_Test"]

with open('Z:\\data2.txt','r+') as infile:
  content = infile.read()
  infile.seek(0,0)
  infile.write("\t".join(headers)+"\n"+content)

I hope this helps.