I have an original text file with 100 rows and 40 columns of data. I would like to write an individual text file for each data row of the original text file.
I can only work out how to do it the long way:
Data = loadtxt('Data.txt')
Row1 = Data[0,:]
np.savetxt('Row1.txt', [Row1])
Row2 = Data[1,:]
np.savetxt('Row2.txt', [Row2])
Row3 = Data[2,:] etc....
Is there a way of using a loop to make this process quicker/do it all at once so I can avoid doing this 100 times?
I was thinking something along the lines of
with open('Data.txt') as f:
for line in f.
line_out = f.readlines():
with open(line + '.txt','w') as fout:
fout.write(line_out)
This doesn't work but I can't work out what the code should be.
You're on the right track. This should give you files with names corresponding to each line number:
counter = 0
with open("sampleInput.txt",'rU') as f:
for i in f:
newFileName = 'newFile_'+str(counter)
outFile = open(newFileName,'w')
outFile.write(i)
outFile.close()
counter+=1
Consider fileNames.txt contain all the words for creating multiple .txt files.
f = open('fileNames.txt', 'r+')
for line in f:
if '\n' in line:
line = line[:-1] #assuming /n at the end of file
new = open("%s.txt"%line,"w+")
new.write("File with name %s"%line) #content for each file.
new.close()
New files will not be created if \\n is present in the string. Hence avoid such conditions. If fileNames.txt contains---> frog four legs
Then three files named frog.txt four.txt and legs.txt will be created.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.