Write First Row From .txt-file As A Column In New .txt-file
I am trying to get the first row of a file.txt (tab separated strings) and create a new file with one column which is made of the elements of the row I want to extract. I managed t
Solution 1:
withopen('inFile.txt', 'r') as inFile, open('outfile.txt', 'w') as outFile:
outFile.writelines(line + '\n'for line in inFile.readline().split('\t'))
To split the file in smaller parts I would use unix split, for example:
split -l $lines_per_file outfile.txt
To find $lines_per_file
divide the total number of lines wc -l output.txt
by 10.
Solution 2:
You could use genfromtxt and savetxt routines:
If you want to save strings (as per the amended question):
import numpy as np
withopen('new_file.txt','w') as f:
for el in np.genfromtxt('file.txt',dtype=None)[0]:
f.write(str(el)+'\n')
If the data is numerical:
import numpy as np
x=np.genfromtxt('file.txt')[0]
np.savetxt('new_file.txt',x)
You could even combine these into one line:
np.savetxt('myfile2.dat',np.genfromtxt('myfile.dat')[0])
Post a Comment for "Write First Row From .txt-file As A Column In New .txt-file"