一个输入文件到多个输出文件

2024-09-24 04:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这个网站上找到了一些有用的东西,但我的输入文件与已经发布的示例不同,我无法以有效的方式实现飞跃。在

我的输入文件如下所示:

sample_dude data1 data2 data3 data4
sample_lady data5 data6 data7 data8
sample_dude data9 data10 data11 data12
sample_child data13 data14 data15 data16

我想为每个示例创建一个包含所有数据列的单独文件。例如,一个文件名为sample_花花公子.txt看起来像这样:

^{pr2}$

样本数量未知,但始终只有四个数据列。在

非常感谢任何帮助。非常感谢。在

PS:我正在尝试用python来实现这一点。在


Tags: 文件数据sample示例网站方式data1data2
3条回答

试试这样的吗?拆分将所有文件名映射到列列表,创建并向每个文件写入行。在

with open('someFile.txt') as f:
  out = {}
  for line in f:
    key, data = line.split(' ', 1)        
    if not key in out.keys():
      out[key] = []
    out[key].append(data)

for k, v in out.items():
  with open(k+'.txt', 'w') as f:
    f.writelines(v)

您可以通过打开文件并遍历每一行来完成此操作。我不会为您编写代码,但这里有一个算法。在

# Open the input file
# Loop through each line of the file
    # Split the line into the file name and the data
    # Open the file name and append the data to the end

您还可以在打开所有文件进行写入之前保存它们的数据。如果有多行文件,这会更快。在

例如:

with open('input.txt') as input:
    for line in input:
        name, data = line.split(' ', 1)

        with open('{0}.txt'.format(name), 'a') as f:
            f.write(data)

相关问题 更多 >