Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印文件中的行,直到行空白_Python_Python 3.x_File_Text_Blank Line - Fatal编程技术网

Python 打印文件中的行,直到行空白

Python 打印文件中的行,直到行空白,python,python-3.x,file,text,blank-line,Python,Python 3.x,File,Text,Blank Line,我有一个文件“testread.txt”,其中包含以下数据 A 1 2 3 4 BA 5 6 7 8 CB 9 10 11 D 12 13 14 15 我想按每个部分读取和提取数据,并将其写入不同的文件。Eg 1 2 3 4 将其写入文件“a.txt” 将其写入文件“b.txt” 将其写入文件“c.txt” 等等…这个想法是在有新的空行可用时跳过文件。下面的代码应该可以做到这一点 files_list = ['a.txt', 'b.txt', 'c.txt'] fpr = open('

我有一个文件“testread.txt”,其中包含以下数据

A
1
2
3
4

BA
5
6
7
8

CB
9
10
11

D
12
13
14
15
我想按每个部分读取和提取数据,并将其写入不同的文件。Eg

1
2
3
4
将其写入文件“a.txt”

将其写入文件“b.txt”

将其写入文件“c.txt”
等等…

这个想法是在有新的空行可用时跳过文件。下面的代码应该可以做到这一点

files_list = ['a.txt', 'b.txt', 'c.txt']
fpr = open('input.txt')
for f in files_list:
    with open(f, 'w') as fpw:
        for i, line in enumerate(fpr):
            if i == 0:   # skips first line
                continue
            if line.strip():
                fpw.write(line)
            else:
                break
可使用以下方法获得(粗略)解决方案:

  • 划分和储存物品
  • 将它们保存到文件中
  • 你会得到:

    • file0.txt
    • file1.txt
    • file2.txt
    • file3.txt

    请提供您的attempt@deppermMCVE仅适用于需要调试的代码,不能假设OP没有说明任何问题或显示任何尝试。无需验证和复制。按换行符拆分并写入it@TrebledJ我试着让OP知道,在要求他做这件事之前,先尝试一下这个问题them@depperm当然可以,但是链接MCVE帮助页面是一个大胆的猜测,即OP有现有代码。据我们所知,可能根本没有编写代码,可能会混淆操作,或者可能更合适。谢谢你Praveen。。。。我还想删除第一行A、BA、CB的标题,并包含每个部分的唯一值。这应该行得通。
    9
    10
    11
    
    files_list = ['a.txt', 'b.txt', 'c.txt']
    fpr = open('input.txt')
    for f in files_list:
        with open(f, 'w') as fpw:
            for i, line in enumerate(fpr):
                if i == 0:   # skips first line
                    continue
                if line.strip():
                    fpw.write(line)
                else:
                    break
    
    import numpy as np
    from collections import defaultdict
    
    with open('testread.txt', 'r') as f:
        content = f.readlines()
    
    d = defaultdict(list)
    
    i = 0
    for line in content:
        if line == '\n':
            i+=1
        else:
            d[i].append(line.strip())
    
    for k,v in d.items():
        np.savetxt('file{}.txt'.format(k), v[1:], delimiter=",", fmt='%s')
    
    1
    2
    3
    4
    
    5
    6
    7
    8
    
    9
    10
    11
    
    12
    13
    14
    15