Python 从原始文本文件中的数据创建多个文本文件
我有一个包含100行40列数据的原始文本文件。 我想为原始文本文件的每个数据行编写一个单独的文本文件 我只能从长远的角度考虑如何做到这一点:Python 从原始文本文件中的数据创建多个文本文件,python,python-2.7,numpy,text,Python,Python 2.7,Numpy,Text,我有一个包含100行40列数据的原始文本文件。 我想为原始文本文件的每个数据行编写一个单独的文本文件 我只能从长远的角度考虑如何做到这一点: Data = loadtxt('Data.txt') Row1 = Data[0,:] np.savetxt('Row1.txt', [Row1]) Row2 = Data[1,:] np.savetxt('Row2.txt', [Row2]) Row3 = Data[2,:] etc.... 有没有一种方法可以使用循环使这个过程更快/一次完成
Data = loadtxt('Data.txt')
Row1 = Data[0,:]
np.savetxt('Row1.txt', [Row1])
Row2 = Data[1,:]
np.savetxt('Row2.txt', [Row2])
Row3 = Data[2,:] etc....
有没有一种方法可以使用循环使这个过程更快/一次完成所有操作,这样我就可以避免执行100次
我在想一些关于
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)
这不起作用,但我无法确定代码应该是什么。您的思路是正确的。这将为您提供与每个行号对应的文件名:
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
你在正确的轨道上。这将为您提供与每个行号对应的文件名:
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
考虑fileNames.txt包含用于创建多个.txt文件的所有单词
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()
如果字符串中存在\n,则不会创建新文件。因此,应避免此类情况。
如果fileNames.txt包含-->青蛙四条腿然后将创建三个名为frog.txt four.txt和legs.txt的文件。考虑fileNames.txt包含创建多个.txt文件的所有单词
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()
如果字符串中存在\n,则不会创建新文件。因此,应避免此类情况。
如果fileNames.txt包含-->青蛙四条腿然后将创建三个名为frog.txt four.txt和legs.txt的文件