Python:基于行数创建文件块

2024-04-20 12:07:33 发布

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

我有一个具有以下视图的文件:

ID Num1 Num2
1   1   2
1   2   4
1   3   6
2   4   8
2   5   10
3   6   12
3   7   14
3   8   16
3   9   18
4   10  20
5   11  22
5   12  24

我想根据每个文件不应包含超过3个ID值的条件将文件拆分为多个文件。因此,在本例中,它们将输出两个文件。第一个文件应具有以下输出:

1   1   2
1   2   4
1   3   6
2   4   8
2   5   10
3   6   12
3   7   14
3   8   16
3   9   18

而第二个文件应该如下所示:

4   10  20
5   11  22
5   12  24

但是它会生成三个文件,其中第二个文件为空文件,第三个文件仅包含ID=5的值。你知道吗

以下代码是用python编写的:

infile=open("Input.txt","r")
outfile=open("Output1.txt","w")

list_value=[] # Storing the values of 1st column
file=2 # Naming the file
value="" # 1st column value
for line in infile:
    value=line.split()[0] 
    if value in list_value:
        outfile.write(line)
    else:
        list_value.append(value)
        if (len(list_value)) < 4:
            outfile.write(line)
        elif (len(list_value))==4:
            outfile=open("Output"+str(file)+".txt","w")
            outfile.write(line)
            file=file+1
            list_value=[]

该代码只在第一个序列中运行良好,但在最后无法运行。你知道吗

任何针对linux的命令也会有所帮助。你知道吗

谢谢!你知道吗


Tags: 文件the代码intxtidvalueline