Change specific value in CSV file via Python












15














I need the way to change specific value of the column of csv file. For example I have csv file:



"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50


and I need to change value 23 to 30 of the "127.0.0.2".



I use csv library: import csv



Appreciate any help as I'm new in Python. Thanks!










share|improve this question






















  • So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
    – ihorko
    Jun 14 '12 at 13:11












  • Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
    – Simeon Visser
    Jun 14 '12 at 13:13
















15














I need the way to change specific value of the column of csv file. For example I have csv file:



"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50


and I need to change value 23 to 30 of the "127.0.0.2".



I use csv library: import csv



Appreciate any help as I'm new in Python. Thanks!










share|improve this question






















  • So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
    – ihorko
    Jun 14 '12 at 13:11












  • Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
    – Simeon Visser
    Jun 14 '12 at 13:13














15












15








15


15





I need the way to change specific value of the column of csv file. For example I have csv file:



"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50


and I need to change value 23 to 30 of the "127.0.0.2".



I use csv library: import csv



Appreciate any help as I'm new in Python. Thanks!










share|improve this question













I need the way to change specific value of the column of csv file. For example I have csv file:



"Ip","Sites"
"127.0.0.1",10
"127.0.0.2",23
"127.0.0.3",50


and I need to change value 23 to 30 of the "127.0.0.2".



I use csv library: import csv



Appreciate any help as I'm new in Python. Thanks!







python csv filereader






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 14 '12 at 13:00









ihorko

3,570206198




3,570206198












  • So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
    – ihorko
    Jun 14 '12 at 13:11












  • Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
    – Simeon Visser
    Jun 14 '12 at 13:13


















  • So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
    – ihorko
    Jun 14 '12 at 13:11












  • Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
    – Simeon Visser
    Jun 14 '12 at 13:13
















So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
– ihorko
Jun 14 '12 at 13:11






So, I can read from csv file and write to csv file, but I haven't an idea how to repace values in existing file...
– ihorko
Jun 14 '12 at 13:11














Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
– Simeon Visser
Jun 14 '12 at 13:13




Could you post the read/write code that you already have? At some point you should have the data in Python and you can modify it there before writing.
– Simeon Visser
Jun 14 '12 at 13:13












3 Answers
3






active

oldest

votes


















30














This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.



r = csv.reader(open('/tmp/test.csv')) # Here your csv file
lines = list(r)


Content of lines:



[['Ip', 'Sites'],
['127.0.0.1', '10'],
['127.0.0.2', '23'],
['127.0.0.3', '50']]


Modifying the values:



lines[2][1] = '30'


Content of lines:



[['Ip', 'Sites'],
['127.0.0.1', '10'],
['127.0.0.2', '30'],
['127.0.0.3', '50']]


Now we only have to write it back to a file



writer = csv.writer(open('/tmp/output.csv', 'w'))
writer.writerows(lines)





share|improve this answer



















  • 1




    If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
    – Nitay
    Mar 4 '15 at 10:28










  • Do you have to close the writer?
    – pekasus
    Jul 13 '17 at 13:57










  • You should close the file descriptor but not the writer. You can use "with" to manage files
    – Diego Navarro
    Jul 17 '17 at 9:56



















11














You can't really replace values in the existing file. Instead, you need to:




  1. read in existing file

  2. alter file in memory

  3. write out new file (overwriting existing file)


What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, close both files, delete the original and rename the new file.






share|improve this answer





























    9














    You can use very powerful library called pandas. Here is the example.



    import pandas as pd
    df = pd.read_csv("test.csv")
    df.head(3) #prints 3 heading rows


    Output:



        Ip  Sites
    0 127.0.0.1 10
    1 127.0.0.2 23
    2 127.0.0.3 50


    Now if you want to change the value in the 'Sites' column in the 1st row, run:



    df.set_value(1, "Sites", 30)


    If you want to change all the values, where 'Ip' is equal to 127.0.0.2, run:



    df.loc[df["Ip"]=="127.0.0.2", "Sites"] = 30


    Finally, to save the values:



    df.to_csv("test.csv", index=False)





    share|improve this answer

















    • 1




      Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
      – Guru
      Mar 30 at 12:34












    • This is not related to this code. It seems that you do not have write permissions to the file.
      – Yury
      Apr 3 at 6:42











    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%2f11033590%2fchange-specific-value-in-csv-file-via-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    30














    This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.



    r = csv.reader(open('/tmp/test.csv')) # Here your csv file
    lines = list(r)


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '23'],
    ['127.0.0.3', '50']]


    Modifying the values:



    lines[2][1] = '30'


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '30'],
    ['127.0.0.3', '50']]


    Now we only have to write it back to a file



    writer = csv.writer(open('/tmp/output.csv', 'w'))
    writer.writerows(lines)





    share|improve this answer



















    • 1




      If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
      – Nitay
      Mar 4 '15 at 10:28










    • Do you have to close the writer?
      – pekasus
      Jul 13 '17 at 13:57










    • You should close the file descriptor but not the writer. You can use "with" to manage files
      – Diego Navarro
      Jul 17 '17 at 9:56
















    30














    This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.



    r = csv.reader(open('/tmp/test.csv')) # Here your csv file
    lines = list(r)


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '23'],
    ['127.0.0.3', '50']]


    Modifying the values:



    lines[2][1] = '30'


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '30'],
    ['127.0.0.3', '50']]


    Now we only have to write it back to a file



    writer = csv.writer(open('/tmp/output.csv', 'w'))
    writer.writerows(lines)





    share|improve this answer



















    • 1




      If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
      – Nitay
      Mar 4 '15 at 10:28










    • Do you have to close the writer?
      – pekasus
      Jul 13 '17 at 13:57










    • You should close the file descriptor but not the writer. You can use "with" to manage files
      – Diego Navarro
      Jul 17 '17 at 9:56














    30












    30








    30






    This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.



    r = csv.reader(open('/tmp/test.csv')) # Here your csv file
    lines = list(r)


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '23'],
    ['127.0.0.3', '50']]


    Modifying the values:



    lines[2][1] = '30'


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '30'],
    ['127.0.0.3', '50']]


    Now we only have to write it back to a file



    writer = csv.writer(open('/tmp/output.csv', 'w'))
    writer.writerows(lines)





    share|improve this answer














    This is the solution opening the csv file, changing the values in memory and then writing back the changes to disk.



    r = csv.reader(open('/tmp/test.csv')) # Here your csv file
    lines = list(r)


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '23'],
    ['127.0.0.3', '50']]


    Modifying the values:



    lines[2][1] = '30'


    Content of lines:



    [['Ip', 'Sites'],
    ['127.0.0.1', '10'],
    ['127.0.0.2', '30'],
    ['127.0.0.3', '50']]


    Now we only have to write it back to a file



    writer = csv.writer(open('/tmp/output.csv', 'w'))
    writer.writerows(lines)






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 31 at 11:14









    Aran-Fey

    20.6k53368




    20.6k53368










    answered Jun 14 '12 at 13:15









    Diego Navarro

    6,31421725




    6,31421725








    • 1




      If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
      – Nitay
      Mar 4 '15 at 10:28










    • Do you have to close the writer?
      – pekasus
      Jul 13 '17 at 13:57










    • You should close the file descriptor but not the writer. You can use "with" to manage files
      – Diego Navarro
      Jul 17 '17 at 9:56














    • 1




      If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
      – Nitay
      Mar 4 '15 at 10:28










    • Do you have to close the writer?
      – pekasus
      Jul 13 '17 at 13:57










    • You should close the file descriptor but not the writer. You can use "with" to manage files
      – Diego Navarro
      Jul 17 '17 at 9:56








    1




    1




    If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
    – Nitay
    Mar 4 '15 at 10:28




    If you run into a double linebreak problem on the written csv, you might want to try openning the file as a binary: writer = csv.writer(open('/tmp/output.csv', 'wb'))
    – Nitay
    Mar 4 '15 at 10:28












    Do you have to close the writer?
    – pekasus
    Jul 13 '17 at 13:57




    Do you have to close the writer?
    – pekasus
    Jul 13 '17 at 13:57












    You should close the file descriptor but not the writer. You can use "with" to manage files
    – Diego Navarro
    Jul 17 '17 at 9:56




    You should close the file descriptor but not the writer. You can use "with" to manage files
    – Diego Navarro
    Jul 17 '17 at 9:56













    11














    You can't really replace values in the existing file. Instead, you need to:




    1. read in existing file

    2. alter file in memory

    3. write out new file (overwriting existing file)


    What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, close both files, delete the original and rename the new file.






    share|improve this answer


























      11














      You can't really replace values in the existing file. Instead, you need to:




      1. read in existing file

      2. alter file in memory

      3. write out new file (overwriting existing file)


      What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, close both files, delete the original and rename the new file.






      share|improve this answer
























        11












        11








        11






        You can't really replace values in the existing file. Instead, you need to:




        1. read in existing file

        2. alter file in memory

        3. write out new file (overwriting existing file)


        What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, close both files, delete the original and rename the new file.






        share|improve this answer












        You can't really replace values in the existing file. Instead, you need to:




        1. read in existing file

        2. alter file in memory

        3. write out new file (overwriting existing file)


        What you can also do is read in the existing file line by line, writing it out to a new file, while replacing values on the fly. When done, close both files, delete the original and rename the new file.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jun 14 '12 at 13:15









        Daren Thomas

        42.1k37130184




        42.1k37130184























            9














            You can use very powerful library called pandas. Here is the example.



            import pandas as pd
            df = pd.read_csv("test.csv")
            df.head(3) #prints 3 heading rows


            Output:



                Ip  Sites
            0 127.0.0.1 10
            1 127.0.0.2 23
            2 127.0.0.3 50


            Now if you want to change the value in the 'Sites' column in the 1st row, run:



            df.set_value(1, "Sites", 30)


            If you want to change all the values, where 'Ip' is equal to 127.0.0.2, run:



            df.loc[df["Ip"]=="127.0.0.2", "Sites"] = 30


            Finally, to save the values:



            df.to_csv("test.csv", index=False)





            share|improve this answer

















            • 1




              Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
              – Guru
              Mar 30 at 12:34












            • This is not related to this code. It seems that you do not have write permissions to the file.
              – Yury
              Apr 3 at 6:42
















            9














            You can use very powerful library called pandas. Here is the example.



            import pandas as pd
            df = pd.read_csv("test.csv")
            df.head(3) #prints 3 heading rows


            Output:



                Ip  Sites
            0 127.0.0.1 10
            1 127.0.0.2 23
            2 127.0.0.3 50


            Now if you want to change the value in the 'Sites' column in the 1st row, run:



            df.set_value(1, "Sites", 30)


            If you want to change all the values, where 'Ip' is equal to 127.0.0.2, run:



            df.loc[df["Ip"]=="127.0.0.2", "Sites"] = 30


            Finally, to save the values:



            df.to_csv("test.csv", index=False)





            share|improve this answer

















            • 1




              Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
              – Guru
              Mar 30 at 12:34












            • This is not related to this code. It seems that you do not have write permissions to the file.
              – Yury
              Apr 3 at 6:42














            9












            9








            9






            You can use very powerful library called pandas. Here is the example.



            import pandas as pd
            df = pd.read_csv("test.csv")
            df.head(3) #prints 3 heading rows


            Output:



                Ip  Sites
            0 127.0.0.1 10
            1 127.0.0.2 23
            2 127.0.0.3 50


            Now if you want to change the value in the 'Sites' column in the 1st row, run:



            df.set_value(1, "Sites", 30)


            If you want to change all the values, where 'Ip' is equal to 127.0.0.2, run:



            df.loc[df["Ip"]=="127.0.0.2", "Sites"] = 30


            Finally, to save the values:



            df.to_csv("test.csv", index=False)





            share|improve this answer












            You can use very powerful library called pandas. Here is the example.



            import pandas as pd
            df = pd.read_csv("test.csv")
            df.head(3) #prints 3 heading rows


            Output:



                Ip  Sites
            0 127.0.0.1 10
            1 127.0.0.2 23
            2 127.0.0.3 50


            Now if you want to change the value in the 'Sites' column in the 1st row, run:



            df.set_value(1, "Sites", 30)


            If you want to change all the values, where 'Ip' is equal to 127.0.0.2, run:



            df.loc[df["Ip"]=="127.0.0.2", "Sites"] = 30


            Finally, to save the values:



            df.to_csv("test.csv", index=False)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 21 '17 at 13:27









            Yury

            17.2k74676




            17.2k74676








            • 1




              Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
              – Guru
              Mar 30 at 12:34












            • This is not related to this code. It seems that you do not have write permissions to the file.
              – Yury
              Apr 3 at 6:42














            • 1




              Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
              – Guru
              Mar 30 at 12:34












            • This is not related to this code. It seems that you do not have write permissions to the file.
              – Yury
              Apr 3 at 6:42








            1




            1




            Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
            – Guru
            Mar 30 at 12:34






            Though it works for most of the time. Sometimes it gives PermissionError: [Errno 13] Permission denied: 'file.csv' Can you suspect what could be the reason?
            – Guru
            Mar 30 at 12:34














            This is not related to this code. It seems that you do not have write permissions to the file.
            – Yury
            Apr 3 at 6:42




            This is not related to this code. It seems that you do not have write permissions to the file.
            – Yury
            Apr 3 at 6:42


















            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%2f11033590%2fchange-specific-value-in-csv-file-via-python%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

            Wiesbaden

            Marschland

            Dieringhausen