值不会出现在CSV下载中

时间:2016-06-10 17:28:11

标签: python csv

我正在使用以下python代码从文件夹中的文本文件中读取并以CSV格式打印:

file = glob.glob(path)
for fle in file:
    # open the file and then call .read() to get the text
    with open(fle) as f:
        lines=f.readlines()
        Date= (lines[6])
        Title=(lines[8])
        print (Date)
        print (Title)

file = glob.glob(path)
for fle in file:
    output = fle.replace('.txt', '')
    X=output
    with open(output+'_tonename.csv', mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1,lineterminator='\n')
        writer.writerows((name, score,Title,Date)
                            for name, score in zip(tonename, tonescore))

但是当我打开最终的CSV文件时,它只显示名称和分数,而不是标题和日期。我很确定这与我的最后一个循环有关,因为当我尝试打印它们确实出现的日期和标题时。我一直在玩这个很多但是无法弄明白,我真的很感激这方面的任何指示。

谢谢

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题,修改后的代码是:

for fle in file:
    # open the file and then call .read() to get the text 

    data=tone_analyzer.tone(text='text')

    # iterate through tone analysis data
    tonename=[]; tonescore=[]
    for cat in data['document_tone']['tone_categories']:
     for tone in cat['tones']:
            tonename.append(tone['tone_name'])
            tonescore.append(tone['score'])
            print(tone['tone_name'],tone['score'])
    # output tone name and score to file


file = glob.glob(path)
for fle in file:
    output = fle.replace('.txt', '') 

    with open(fle) as f:
     lines=f.readlines()
     Date= (lines[6])
     Title=(lines[8])
     X=output
    with open(output+'_tonename.csv', mode = 'w') as csvfile1:
        writer = csv.writer(csvfile1,lineterminator='\n') 
        writer.writerows((name, score,Title,Date) for name, score in zip(tonename, tonescore))