【问题标题】:Only outputting a few lines into a text file, instead of all of them仅将几行输出到文本文件中,而不是全部输出
【发布时间】:2017-04-06 00:57:08
【问题描述】:

我制作了一个 Python 脚本,该脚本从 .csv 存档中获取信息,并将其作为列表输出到文本文件中。原始 csv 文件有超过 200,000 个字段可供输入和输出,但是当我运行我的程序时,它只将 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 文件太大了?

【问题讨论】:

  • 没有您的输入和输出文件,我们对可能发生的事情一无所知。至少,检查 CSV 文件的格式。
  • csv 文件超过 230,000 行,所有信息由每个字段的逗号分隔 - 脚本收集它们并将它们输出到 txt 文件,如下所示:pastebin.com/L6KzWYev
  • 在此处打印前 37 行,以便我们重现错误
  • 导出的 txt 文件看起来像我链接的那个 pastebin。虽然原始 csv 文件有 200,000 行,但像这样:john paul,johnpaul@gmail.com,202,909,2016-08-21 11:12:33- 我只从中取出电子邮件
  • 它停止的value of next input 是什么? I guess you're error is with the input!!!

标签: python csv


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    您可能会遇到以下情况:

    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')
    

    【讨论】:

    • 为什么op会有更好的运气?
    • 它显示了同样多的结果,而不是只打印 csv 文件中的电子邮件,它导出了我不想要的所有内容。
    • 另外,使用单个 with 块,用逗号分隔上下文管理器
    • @mad-physicist 这样更好吗?
    • 不,我的意思是你应该这样做 with open(..) as csvfile, open(...) as output: 并以这种方式消除嵌套级别。
    猜你喜欢
    • 2016-09-17
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多