Python 仅将几行输出到文本文件中,而不是全部输出

Python 仅将几行输出到文本文件中,而不是全部输出,python,csv,Python,Csv,我制作了一个Python脚本,它从.csv存档中获取信息,并将其作为列表输出到文本文件中。原始csv文件有200000多个字段可供输入和输出,但当我运行程序时,它只将36个字段输出到.txt文件中 代码如下: import csv with open('OriginalFile.csv', 'r') as csvfile: emailreader = csv.reader(csvfile) f = open('text.txt', 'a') for row in emai

我制作了一个Python脚本,它从.csv存档中获取信息,并将其作为列表输出到文本文件中。原始csv文件有200000多个字段可供输入和输出,但当我运行程序时,它只将36个字段输出到.txt文件中

代码如下:

import csv
with open('OriginalFile.csv', 'r') as csvfile:
    emailreader = csv.reader(csvfile)
    f = open('text.txt', 'a')
    for row in emailreader:
        f.write(row[1] + "\n")

文本文件最多只列出36个字符串。我怎样才能解决这个问题?可能是原始csv文件太大了吗?

您可能会遇到以下情况:

with open('OriginalFile.csv', 'r') as csvfile:
    emailreader = csv.reader(csvfile)
    with open('text.txt','w') as output:
    for line in emailreader:
        output.write(line[1]+'\n')

经过多次注释,最初的问题是csv文件中字符的编码。如果您在pandas中指定编码,它将很好地读取它

每当您处理csv文件(或excel、sql或R)时,我都会使用Pandas数据帧。语法更短,更容易知道发生了什么

import pandas as pd
csvframe = pd.read_csv('OriginalFile.csv', encoding='utf-8')
with open('text.txt', 'a') as output:
    # I think what you wanted was the 2nd column from each row
    output.write('\n'.join(csvframe.ix[:,1].values))
    # the ix is for index and : is for all the rows and the 1 is only the first column

没有您的输入和输出文件,我们对可能发生的事情一无所知。至少,检查您的CSV文件的格式。CSV文件超过230000行,所有信息按字段用逗号分隔-脚本收集它们并将它们输出到txt文件,如下所示:在此处打印前37行,以便我们可以重现错误导出的txt文件看起来像我链接的粘贴文件。原始csv文件有200000行,如下所示:john paul,johnpaul@gmail.com,2029092016-08-21 11:12:33-我只从中取出电子邮件下次输入的
值是多少<代码>我猜您的错误在于输入
!!!为什么op会有更好的运气?它显示同样多的结果,而不是只打印csv文件中的电子邮件,它导出了我不想要的所有内容。此外,使用一个with块,使用更好的@mad Physicast命令分隔上下文管理器?不,我的意思是你可能应该像csvfile一样使用open(..)执行
,将(…)作为输出打开:
并以这种方式消除嵌套级别。