使用python拆分文件

2024-06-25 22:55:26 发布

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

import csv
import os
mycsv =csv.reader(open("IF_1027_SampleFile.csv","r"))
mycsv1 =csv.reader(open("Output","a"))
search_query ='Record Detail'
line =mycsv.readline()
if line==Searchquery:
    mycsv1.write(line)
    line =mycsv.readline()
else
    infile.close()
    outfile.close()

现在我得到以下错误:

SyntaxError: ("mismatched input 'mycsv1' expecting INDENT", ('<string>', 9, 0, 'mycsv1.write(line)\n'))

你能帮我一下吗。我哪里做错了?你知道吗


Tags: csvimportcloseoutputsearchreadlineifos
1条回答
网友
1楼 · 发布于 2024-06-25 22:55:26

对你的预期产出不是很确定。你知道吗

根据你的评论,我假设如下:

输入文件 -样本数据

record header               
col1    col2    col3        
1              2       3        
2              3       4        
Record Detail               
col1    col2    col3    col4    col5
1           2      3        4       5
2           3      4        5       6

预期输出 记录详细信息后的所有行。你知道吗

    col1    col2    col3    col4    col5
    1      2       3       4       5
    2      3       4       5       6

代码

由于原始代码存在一些问题,我编写了以下简化版本:

outfile = open('Output','a')

Searchquery = 'Record Detail'
flag = 0

with open('IF_1027_SampleFile.csv','r') as infile:
    for row in infile:
        if ( not flag):
            if Searchquery in row:            #checks for Searchquery
                flag = 1                      #raises flag
        else:
            outfile.write(row)                #if flag is 1, then write to file


outfile.close()   

代码打开输入文件,检查搜索查询的每一行,并将搜索查询后的行写入输出文件。你知道吗

相关问题 更多 >