【问题标题】:How can I create a new file for each n line occurance如何为每 n 行出现创建一个新文件
【发布时间】:2022-01-21 22:45:13
【问题描述】:

我有这样的数据:

ID 1
x y
3 4
4 3
6 8
ID 2
x y
3 4
4 3
6 8
.
.
.
ID 100
x y
2 40
41 32
6 8

我想为每个 ID 创建一个数据文件,例如 ID_1.txt、ID_2.txt... 我的代码是:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
###############################################

fichier = "data.txt"
file = open(fichier).read().split('\n')
n =0
j=0
id=[]
for i in file :
    # print("********",i)
    current_id = j+1
    if 'ID' in i:
        id.append(n+1)
        print('n=',n)
        globals()[f'ID_{n}']=[]
        n+=1

    while current_id == id[-1] :
        
        if i.find('ID'):
            print(i.find('ID'))
            eval()[f'ID_{n}'].append(i)

我仍然得到一个空的 ID_{n} 列表,知道吗?

谢谢。

【问题讨论】:

    标签: python list dataframe readline


    【解决方案1】:

    你走在正确的轨道上,但你把它弄得太复杂了。打开要读取的文件并遍历行,检查该行中的'ID' 以打开一个新文件进行写入。

    from io import StringIO
    
    # just make a generic file-like object to start with
    writer = StringIO()
    
    with open('data.txt') as fp:
        for line in fp:
            if line.startswith('ID'):
                writer.close()
                filename = line.strip().replace(' ', '_') + '.txt'
                writer = open(filename, 'w')
            writer.write(line)
        writer.close()
    

    【讨论】:

    • 感谢您的帮助,现在可以使用了。
    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 2020-06-19
    • 2020-09-28
    • 1970-01-01
    • 2018-03-12
    • 2013-06-07
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多