从.txt中提取数据并将其写入.csv

时间:2017-11-21 17:05:22

标签: python csv

我有一个带有json推文的txt文件, 每条推文都在[" text":& " is_quote_status&#34 ;:] 我已经设法提取了推文,现在我想逐行将打印输出写入csv。

import csv
with open('trumpT.csv', "wb") as csvfile:
    writer = csv.writer(trumpT.csv, delimiter=',')
with open('sim.txt', 'rb') as f:
    for line in f:
        line.split('"text" :')[1].split(', "is_quote_status')[0]
        writer.writerow(line)

错误     writer = csv.writer(trumpT.csv,delimiter =',')     NameError:name' trumpT'未定义

我能够正确使用这部分,但csv无效吗?

with open('sim.txt', 'rb') as f:
    for line in f:
        print line.split('"text" :')[1].split(', "is_quote_status')[0]

3 个答案:

答案 0 :(得分:1)

试试这个:

import csv

with open("sim.txt", "r", newline='', encoding='utf8') as in_txt:
        in_reader = csv.reader(in_txt, delimiter = '\t')
        with open("trumpT.csv", "w", encoding='utf-8') as out_csv:
            out_writer = csv.writer(out_csv)
            for row in in_reader:
                row.split('"text" :')[1].split(', "is_quote_status')[0]
                out_writer.writerow(row)

答案 1 :(得分:0)

使用with时,请注意直到需要该对象为止,

  然后,Python将执行代码体,无论代码中发生什么,都要调用guard对象的 exit 方法。

所以你必须在with语句的主体中做所有事情 您的代码应如下所示:

import csv
with open('trumpT.csv', "wb") as csvfile, open('sim.txt', 'rb') as f:       
    writer = csv.writer(trumpT.csv, delimiter=',')
    for line in f:
        line.split('"text" :')[1].split(', "is_quote_status')[0]
        writer.writerow(line)

来源:

http://effbot.org/zone/python-with-statement.htm https://docs.python.org/3/reference/compound_stmts.html#the-with-statement

答案 2 :(得分:0)

使用Pandas

可以简化此过程

考虑到/path/to/input.json/path/to/input.txt有一个有效的json文件,文件扩展名并不重要,只要有效的json存在。

import pandas as pd

df = pd.read_json("path/to/input.txt")
df[["text", "created_at_date"]].to_csv("output.csv", index=False)