csv.writer is writing values for one key but not for all the others












1














I have a csv file with rows of key pairs.



Let us call key, 'key' and the different values 'a', 'b', 'c', etc..



I am trying to use csv.writer so that it writes the row onto a file only if the value is 'b'.



I have the following code so far:



csvfileR = 

with open('csvfileR.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
csvfileR.append(row)

w = open('csvfileW.csv','w')
fieldnames = ['key']
writer = csv.writer(w)
writer.writerow(fieldnames)

for i in range(len(csvfileR)):
if csvfileR[i]['key'] == 'b':
print (csvfileR[i]['key'])
fields = [csvfileR[i]['key']]
writer.writerow(fields)


The issue is that writer writes correctly when we filter for value 'a' (if csvfileR[i]['key'] == 'a') but gives a blank csv file when we filter for any other value (if csvfileR[i]['key'] == 'b' (or 'c' or 'd' etc)).



The print method works correctly for all values so the Dict is appended correctly.



Specifically, csvfileR contains data of my asset trades. I want csv.writer to create 'csvfileW' with trade data for only one asset in a series of different assets.



One row of csvfileR would look like:



OrderedDict([('Date', '2016.09.12'), ('Name of Asset Traded', 'Facebook Stock'), ('Price purchased', '$100'), ('Price sold, '$150')



The issue is that csv.writer will write if I filter out for my first asset 'Facebook Stock', but will not write if I filter out for any other asset.



So



if csvfileR[i]['Name of Asset Traded'] == 'Facebook Stock'



will create a CSV file correctly but,



if csvfileR[i]['Name of Asset Traded'] == 'Apple Stock'



or



if csvfileR[i]['Name of Asset Traded'] == 'FedEx Stock'



will create a blank CSV file.



However,



print (csvfileR[i]['Name of Asset Traded'])



will print out 'Apple' or ''FedEx' each time it runs into it.










share|improve this question
























  • Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
    – Martin Evans
    Nov 22 at 11:11










  • Hey Martin, I have edited my post with more details.
    – Nick Oh
    Nov 28 at 3:05










  • Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
    – Martin Evans
    Nov 28 at 11:08
















1














I have a csv file with rows of key pairs.



Let us call key, 'key' and the different values 'a', 'b', 'c', etc..



I am trying to use csv.writer so that it writes the row onto a file only if the value is 'b'.



I have the following code so far:



csvfileR = 

with open('csvfileR.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
csvfileR.append(row)

w = open('csvfileW.csv','w')
fieldnames = ['key']
writer = csv.writer(w)
writer.writerow(fieldnames)

for i in range(len(csvfileR)):
if csvfileR[i]['key'] == 'b':
print (csvfileR[i]['key'])
fields = [csvfileR[i]['key']]
writer.writerow(fields)


The issue is that writer writes correctly when we filter for value 'a' (if csvfileR[i]['key'] == 'a') but gives a blank csv file when we filter for any other value (if csvfileR[i]['key'] == 'b' (or 'c' or 'd' etc)).



The print method works correctly for all values so the Dict is appended correctly.



Specifically, csvfileR contains data of my asset trades. I want csv.writer to create 'csvfileW' with trade data for only one asset in a series of different assets.



One row of csvfileR would look like:



OrderedDict([('Date', '2016.09.12'), ('Name of Asset Traded', 'Facebook Stock'), ('Price purchased', '$100'), ('Price sold, '$150')



The issue is that csv.writer will write if I filter out for my first asset 'Facebook Stock', but will not write if I filter out for any other asset.



So



if csvfileR[i]['Name of Asset Traded'] == 'Facebook Stock'



will create a CSV file correctly but,



if csvfileR[i]['Name of Asset Traded'] == 'Apple Stock'



or



if csvfileR[i]['Name of Asset Traded'] == 'FedEx Stock'



will create a blank CSV file.



However,



print (csvfileR[i]['Name of Asset Traded'])



will print out 'Apple' or ''FedEx' each time it runs into it.










share|improve this question
























  • Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
    – Martin Evans
    Nov 22 at 11:11










  • Hey Martin, I have edited my post with more details.
    – Nick Oh
    Nov 28 at 3:05










  • Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
    – Martin Evans
    Nov 28 at 11:08














1












1








1







I have a csv file with rows of key pairs.



Let us call key, 'key' and the different values 'a', 'b', 'c', etc..



I am trying to use csv.writer so that it writes the row onto a file only if the value is 'b'.



I have the following code so far:



csvfileR = 

with open('csvfileR.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
csvfileR.append(row)

w = open('csvfileW.csv','w')
fieldnames = ['key']
writer = csv.writer(w)
writer.writerow(fieldnames)

for i in range(len(csvfileR)):
if csvfileR[i]['key'] == 'b':
print (csvfileR[i]['key'])
fields = [csvfileR[i]['key']]
writer.writerow(fields)


The issue is that writer writes correctly when we filter for value 'a' (if csvfileR[i]['key'] == 'a') but gives a blank csv file when we filter for any other value (if csvfileR[i]['key'] == 'b' (or 'c' or 'd' etc)).



The print method works correctly for all values so the Dict is appended correctly.



Specifically, csvfileR contains data of my asset trades. I want csv.writer to create 'csvfileW' with trade data for only one asset in a series of different assets.



One row of csvfileR would look like:



OrderedDict([('Date', '2016.09.12'), ('Name of Asset Traded', 'Facebook Stock'), ('Price purchased', '$100'), ('Price sold, '$150')



The issue is that csv.writer will write if I filter out for my first asset 'Facebook Stock', but will not write if I filter out for any other asset.



So



if csvfileR[i]['Name of Asset Traded'] == 'Facebook Stock'



will create a CSV file correctly but,



if csvfileR[i]['Name of Asset Traded'] == 'Apple Stock'



or



if csvfileR[i]['Name of Asset Traded'] == 'FedEx Stock'



will create a blank CSV file.



However,



print (csvfileR[i]['Name of Asset Traded'])



will print out 'Apple' or ''FedEx' each time it runs into it.










share|improve this question















I have a csv file with rows of key pairs.



Let us call key, 'key' and the different values 'a', 'b', 'c', etc..



I am trying to use csv.writer so that it writes the row onto a file only if the value is 'b'.



I have the following code so far:



csvfileR = 

with open('csvfileR.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
csvfileR.append(row)

w = open('csvfileW.csv','w')
fieldnames = ['key']
writer = csv.writer(w)
writer.writerow(fieldnames)

for i in range(len(csvfileR)):
if csvfileR[i]['key'] == 'b':
print (csvfileR[i]['key'])
fields = [csvfileR[i]['key']]
writer.writerow(fields)


The issue is that writer writes correctly when we filter for value 'a' (if csvfileR[i]['key'] == 'a') but gives a blank csv file when we filter for any other value (if csvfileR[i]['key'] == 'b' (or 'c' or 'd' etc)).



The print method works correctly for all values so the Dict is appended correctly.



Specifically, csvfileR contains data of my asset trades. I want csv.writer to create 'csvfileW' with trade data for only one asset in a series of different assets.



One row of csvfileR would look like:



OrderedDict([('Date', '2016.09.12'), ('Name of Asset Traded', 'Facebook Stock'), ('Price purchased', '$100'), ('Price sold, '$150')



The issue is that csv.writer will write if I filter out for my first asset 'Facebook Stock', but will not write if I filter out for any other asset.



So



if csvfileR[i]['Name of Asset Traded'] == 'Facebook Stock'



will create a CSV file correctly but,



if csvfileR[i]['Name of Asset Traded'] == 'Apple Stock'



or



if csvfileR[i]['Name of Asset Traded'] == 'FedEx Stock'



will create a blank CSV file.



However,



print (csvfileR[i]['Name of Asset Traded'])



will print out 'Apple' or ''FedEx' each time it runs into it.







python python-3.x csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 at 3:05

























asked Nov 20 at 23:36









Nick Oh

133




133












  • Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
    – Martin Evans
    Nov 22 at 11:11










  • Hey Martin, I have edited my post with more details.
    – Nick Oh
    Nov 28 at 3:05










  • Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
    – Martin Evans
    Nov 28 at 11:08


















  • Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
    – Martin Evans
    Nov 22 at 11:11










  • Hey Martin, I have edited my post with more details.
    – Nick Oh
    Nov 28 at 3:05










  • Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
    – Martin Evans
    Nov 28 at 11:08
















Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
– Martin Evans
Nov 22 at 11:11




Could you edit the question to show a few lines from csvFileR.csv and what output you are trying to get.
– Martin Evans
Nov 22 at 11:11












Hey Martin, I have edited my post with more details.
– Nick Oh
Nov 28 at 3:05




Hey Martin, I have edited my post with more details.
– Nick Oh
Nov 28 at 3:05












Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
– Martin Evans
Nov 28 at 11:08




Thanks for the update. As I said, it would be useful if you could copy paste (exactly) some lines from your csvFileR.csv file, I would then be able to recreate your problem and find out what the problem might be. The code you have seems ok so the issue might be in the CSV file.
– Martin Evans
Nov 28 at 11:08












2 Answers
2






active

oldest

votes


















0














As mentioned consider using one single with to handle read and write of both files and even avoid the need of the csvfileR list.



with open('csvfileR.csv', 'r') as csvfile, open('csvfileW.csv', 'w') as outfile:
fieldnames = ['key']
writer = csv.writer(outfile)
writer.writerow(fieldnames)

reader = csv.DictReader(csvfile)

for row in reader:
if row['key'] == 'b':
print (row['key'])
fields = [row['key']]
writer.writerow(fields)


However, code above seems strange as only b would output in first column of output csv. Likely, post does not reflect actual code. Adjust above as needed.






share|improve this answer





























    0














    Just figured it out. Very silly mistake. Did not include w.close() at the end of the code. Code works fine now. Thank you for your help.






    share|improve this answer





















    • Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
      – Parfait
      Nov 29 at 13:44











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403219%2fcsv-writer-is-writing-values-for-one-key-but-not-for-all-the-others%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    As mentioned consider using one single with to handle read and write of both files and even avoid the need of the csvfileR list.



    with open('csvfileR.csv', 'r') as csvfile, open('csvfileW.csv', 'w') as outfile:
    fieldnames = ['key']
    writer = csv.writer(outfile)
    writer.writerow(fieldnames)

    reader = csv.DictReader(csvfile)

    for row in reader:
    if row['key'] == 'b':
    print (row['key'])
    fields = [row['key']]
    writer.writerow(fields)


    However, code above seems strange as only b would output in first column of output csv. Likely, post does not reflect actual code. Adjust above as needed.






    share|improve this answer


























      0














      As mentioned consider using one single with to handle read and write of both files and even avoid the need of the csvfileR list.



      with open('csvfileR.csv', 'r') as csvfile, open('csvfileW.csv', 'w') as outfile:
      fieldnames = ['key']
      writer = csv.writer(outfile)
      writer.writerow(fieldnames)

      reader = csv.DictReader(csvfile)

      for row in reader:
      if row['key'] == 'b':
      print (row['key'])
      fields = [row['key']]
      writer.writerow(fields)


      However, code above seems strange as only b would output in first column of output csv. Likely, post does not reflect actual code. Adjust above as needed.






      share|improve this answer
























        0












        0








        0






        As mentioned consider using one single with to handle read and write of both files and even avoid the need of the csvfileR list.



        with open('csvfileR.csv', 'r') as csvfile, open('csvfileW.csv', 'w') as outfile:
        fieldnames = ['key']
        writer = csv.writer(outfile)
        writer.writerow(fieldnames)

        reader = csv.DictReader(csvfile)

        for row in reader:
        if row['key'] == 'b':
        print (row['key'])
        fields = [row['key']]
        writer.writerow(fields)


        However, code above seems strange as only b would output in first column of output csv. Likely, post does not reflect actual code. Adjust above as needed.






        share|improve this answer












        As mentioned consider using one single with to handle read and write of both files and even avoid the need of the csvfileR list.



        with open('csvfileR.csv', 'r') as csvfile, open('csvfileW.csv', 'w') as outfile:
        fieldnames = ['key']
        writer = csv.writer(outfile)
        writer.writerow(fieldnames)

        reader = csv.DictReader(csvfile)

        for row in reader:
        if row['key'] == 'b':
        print (row['key'])
        fields = [row['key']]
        writer.writerow(fields)


        However, code above seems strange as only b would output in first column of output csv. Likely, post does not reflect actual code. Adjust above as needed.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 29 at 17:14









        Parfait

        49.3k84168




        49.3k84168

























            0














            Just figured it out. Very silly mistake. Did not include w.close() at the end of the code. Code works fine now. Thank you for your help.






            share|improve this answer





















            • Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
              – Parfait
              Nov 29 at 13:44
















            0














            Just figured it out. Very silly mistake. Did not include w.close() at the end of the code. Code works fine now. Thank you for your help.






            share|improve this answer





















            • Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
              – Parfait
              Nov 29 at 13:44














            0












            0








            0






            Just figured it out. Very silly mistake. Did not include w.close() at the end of the code. Code works fine now. Thank you for your help.






            share|improve this answer












            Just figured it out. Very silly mistake. Did not include w.close() at the end of the code. Code works fine now. Thank you for your help.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 29 at 1:56









            Nick Oh

            133




            133












            • Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
              – Parfait
              Nov 29 at 13:44


















            • Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
              – Parfait
              Nov 29 at 13:44
















            Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
            – Parfait
            Nov 29 at 13:44




            Context manager using with avoids the need of close. In fact, you can combine both open in same with clause.
            – Parfait
            Nov 29 at 13:44


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403219%2fcsv-writer-is-writing-values-for-one-key-but-not-for-all-the-others%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            Refactoring coordinates for Minecraft Pi buildings written in Python