I have a file containing data like below:
88_NPDJ 565 789 3434 54454
98HGJDN 945 453 3453 23423
...
...
...
whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited.
I have a file containing data like below:
88_NPDJ 565 789 3434 54454
98HGJDN 945 453 3453 23423
...
...
...
whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited.
I am assuming that you already know what the headers are and you just want a way to programmatically insert them at the top of the file.
One way is to read the file into memory, truncate it, write the headers then write back the contents of the file. This might not work so well if the file is huge. If that could be the case, then you could write the header to a new file, then read each line from the original file and append it to the new file, then finally rename the new file so that it replaces the old file.
Best way to get the effect of altering a file in place
is with fileinput:
import fileinput
headers = 'a b c d e'.split()
for line in fileinput.input(['thefile.blah'], inplace=True):
if fileinput.isfirstline():
print '\t'.join(headers)
print line,
Which kind of headers? Something like:
type A Type B Type C Type D Type E
88_NPDJ 565 789 3434 54454
98HGJDN 945 453 3453 23423
...
...
...
Isn't it?
You can open a temporary file, write the headers and then append the rest of the file to your temporary file. Delete the original file and rename the temp. like the original.
import os
headers = ['type 1', 'type 2', 'insert more types']
filename = 'your/file/here'
tmp = open('TMP', 'w')
orig = open(filename, 'r')
tmp.write('\t'.join(headers) + '\n')
for line in orig.readlines():
tmp.write(line)
orig.close()
tmp.close()
os.remove(filename)
os.rename('TMP', filename)