简体   繁体   English

Python 只在新的 csv 文件中写入最后一行

[英]Python writes only last line in the new csv file

I have only last line written in a new csv file.我只有最后一行写在一个新的 csv 文件中。

f = open(r'dataset.csv', encoding="utf8")
data = f.readlines()

tagged_list = []

for line in data:
    tokens = nltk.word_tokenize(line)
    tagged = nltk.pos_tag(tokens)
    adj = [word for word,pos in tagged \
            if (pos == 'JJ' or pos == 'JJR' or pos == 'JJS')]
    downcased = [x.lower() for x in adj]
    joined = " ".join(downcased).encode('utf-8')
    into_string = str(adj)

output = open("out.csv", "wb")
output.write(joined)
output.close()

When I change output = open("out.csv", "a") or output = open("out.csv", "r") I m getting error当我更改output = open("out.csv", "a")output = open("out.csv", "r")我收到错误

Traceback (most recent call last):
  File "nl.py", line 21, in <module>
    output.write(joined)
TypeError: write() argument must be str, not bytes

How can I make it write all the lines one after another and not only the last line.我怎样才能让它一个接一个地写出所有的行,而不仅仅是最后一行。

Open both files, and write the lines as you generate them (untested):打开这两个文件,并在生成它们时写下这些行(未经测试):

with open('dataset.csv', encoding='utf8') as data:
    with open('out.csv','w',encoding='utf8') as output:
        for line in data:
            tokens = nltk.word_tokenize(line)
            tagged = nltk.pos_tag(tokens)
            adj = [word for word,pos in tagged
                   if (pos == 'JJ' or pos == 'JJR' or pos == 'JJS')]
            downcased = [x.lower() for x in adj]
            joined = " ".join(downcased) + '\n'
            output.write(joined)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM