Aschente
Aschente

Reputation: 105

Writing the output to a different csv file column

I have some vocabulary and their counterparts to create an Anki deck. I need the program to write the output of my code in two columns of a csv file; first for the vocabulary and second for the meaning. I've tried two codes but neither of them worked. How can I solve this problem?

Notebook content(vocab):

obligatory,義務的
sole,単独,唯一
defined,一定
obey,従う
...

First try:

with open("C:/Users/berka/Desktop/Vocab.txt") as csv_file:
    csv_reader = csv.reader(csv_file)

    with open("C:/Users/berka/Desktop/v.csv", "w", newline="") as new_file:
        csv_writer = csv.writer(new_file, delimiter=",")

        for line in csv_reader:
            csv_writer.writerow(line)

Second try:

with open("C:/Users/berka/Desktop/Vocab.txt") as csv_file:
    csv_reader = csv.DictReader(csv_file)

    with open("C:/Users/berka/Desktop/v.csv", "w",) as f:
        field_names = ["Vocabulary", "Meaning"]

        csv_writer = csv.DictWriter(f, fieldnames=field_names, extrasaction="ignore")

        csv_writer.writeheader()

        for line in csv_reader:
            csv_writer.writerow(line)

Result of the first try: https://cdn.discordapp.com/attachments/696432733882155138/746404430123106374/unknown.png

#Second try was not even close

Expected result: https://cdn.discordapp.com/attachments/734460259560849542/746432094825087086/unknown.png

Upvotes: 0

Views: 40

Answers (2)

Safa LEVENTOĞLU
Safa LEVENTOĞLU

Reputation: 26

Like Kevin said, Excel uses ";" as delimiter and your csv code creates a csv file with comma(,) delimiter. That's why it's shown with commas in your Csv Reader. You can pass ";" as delimiter if you want Excel to read your file correctly. Or you can create a csv file with your own Csv Reader and read it with notepad if you want to see which delimiter it uses.

Upvotes: 1

Kevin Eaverquepedo
Kevin Eaverquepedo

Reputation: 652

Your first try works, it's the app you're using for importing that is not recognizing the , as the delimiter. I'm not sure where you're importing this to, but at least in Google Sheets you can choose what the delimiter is, even after the fact.

Upvotes: 0

Related Questions