How to turn text file into python list formHow can I check the version of sed in OS X?How do I check if a list is empty?How do I check whether a file exists without exceptions?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?

Draw a checker pattern with a black X in the center

Can a wire having a 610-670 THz (frequency of blue light) AC frequency supply, generate blue light?

What does "tea juice" mean in this context?

How can I grammatically understand "Wir über uns"?

Biblical Basis for 400 years of silence between old and new testament

The deliberate use of misleading terminology

Adding strings in lists together

What does "Marchentalender" on the front of a postcard mean?

What are the slash markings on Gatwick's 08R/26L?

Humans meet a distant alien species. How do they standardize? - Units of Measure

Can an old DSLR be upgraded to match modern smartphone image quality

How to detach yourself from a character you're going to kill?

Self-Preservation: How to DM NPCs that Love Living?

60s (or earlier) short story where each colony has one person who doesn't connect well with others who is there for being able to absorb knowledge

Why does the UK have more political parties than the US?

Is a hash a zero-knowledge proof?

What's the most polite way to tell a manager "shut up and let me work"?

Is there an evolutionary advantage to having two heads?

Why do Russians call their women expensive ("дорогая")?

Uncommanded roll at high speed

What caused the tendency for conservatives to not support climate change regulations?

What does the behaviour of water on the skin of an aircraft in flight tell us?

Do creatures all have the same statistics upon being reanimated via the Animate Dead spell?

Can't connect to Internet in bash using Mac OS



How to turn text file into python list form


How can I check the version of sed in OS X?How do I check if a list is empty?How do I check whether a file exists without exceptions?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?Getting the last element of a list in PythonHow to make a flat list out of list of listsHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?How do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm trying to turn a list of numbers in a text file into python list form. For example, I want to make



1
2
3
4
5


into



[1,2,3,4,5]


I found something that almost worked in another post using sed.



sed '1s/^/[/;$!s/$/,/;$s/$/]/' file


but this didn't remove the new line after every number. How can I modify this sed command to get it to do what I want. Also, an explanation on the components of the sed command would also be appreciated. Thanks










share|improve this question






















  • with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

    – han solo
    Mar 23 at 15:18







  • 8





    Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

    – Jon Clements
    Mar 23 at 15:21












  • Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

    – PS.
    Mar 23 at 15:31











  • Append | tr -d 'n'?

    – Cyrus
    Mar 23 at 15:56











  • Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

    – Joshua Segal
    Mar 23 at 21:00


















0















I'm trying to turn a list of numbers in a text file into python list form. For example, I want to make



1
2
3
4
5


into



[1,2,3,4,5]


I found something that almost worked in another post using sed.



sed '1s/^/[/;$!s/$/,/;$s/$/]/' file


but this didn't remove the new line after every number. How can I modify this sed command to get it to do what I want. Also, an explanation on the components of the sed command would also be appreciated. Thanks










share|improve this question






















  • with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

    – han solo
    Mar 23 at 15:18







  • 8





    Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

    – Jon Clements
    Mar 23 at 15:21












  • Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

    – PS.
    Mar 23 at 15:31











  • Append | tr -d 'n'?

    – Cyrus
    Mar 23 at 15:56











  • Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

    – Joshua Segal
    Mar 23 at 21:00














0












0








0


1






I'm trying to turn a list of numbers in a text file into python list form. For example, I want to make



1
2
3
4
5


into



[1,2,3,4,5]


I found something that almost worked in another post using sed.



sed '1s/^/[/;$!s/$/,/;$s/$/]/' file


but this didn't remove the new line after every number. How can I modify this sed command to get it to do what I want. Also, an explanation on the components of the sed command would also be appreciated. Thanks










share|improve this question














I'm trying to turn a list of numbers in a text file into python list form. For example, I want to make



1
2
3
4
5


into



[1,2,3,4,5]


I found something that almost worked in another post using sed.



sed '1s/^/[/;$!s/$/,/;$s/$/]/' file


but this didn't remove the new line after every number. How can I modify this sed command to get it to do what I want. Also, an explanation on the components of the sed command would also be appreciated. Thanks







python list sed






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 15:17









Joshua SegalJoshua Segal

62




62












  • with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

    – han solo
    Mar 23 at 15:18







  • 8





    Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

    – Jon Clements
    Mar 23 at 15:21












  • Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

    – PS.
    Mar 23 at 15:31











  • Append | tr -d 'n'?

    – Cyrus
    Mar 23 at 15:56











  • Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

    – Joshua Segal
    Mar 23 at 21:00


















  • with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

    – han solo
    Mar 23 at 15:18







  • 8





    Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

    – Jon Clements
    Mar 23 at 15:21












  • Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

    – PS.
    Mar 23 at 15:31











  • Append | tr -d 'n'?

    – Cyrus
    Mar 23 at 15:56











  • Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

    – Joshua Segal
    Mar 23 at 21:00

















with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

– han solo
Mar 23 at 15:18






with open('file') as f:..data = f.read().strip().split();..nums = map(int, data) ? Why are you using sed here ?

– han solo
Mar 23 at 15:18





8




8





Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

– Jon Clements
Mar 23 at 15:21






Are you wanting to do this in Python or is this primarily a question on sed and you're just referencing Python because of the format? If the later - you don't need anything except the sed tag... and if the former - you'd don't need the sed tag... Please considering making an edit to your post to clarify that - thanks.

– Jon Clements
Mar 23 at 15:21














Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

– PS.
Mar 23 at 15:31





Just in case you need it for some out of python operation awk 'BEGINRS=ORS="";OFS="," ;printf "[" $1=$1;print ENDprint "]n"' file

– PS.
Mar 23 at 15:31













Append | tr -d 'n'?

– Cyrus
Mar 23 at 15:56





Append | tr -d 'n'?

– Cyrus
Mar 23 at 15:56













Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

– Joshua Segal
Mar 23 at 21:00






Thank you @Cyrus. That's a pretty good command line answer. You should make it an actual answer

– Joshua Segal
Mar 23 at 21:00













4 Answers
4






active

oldest

votes


















1














With GNU sed for -z to read the whole file at once:



sed -z 's/n/,/g; s/^/[/; s/,$/]n/' file
[1,2,3,4,5]


With any awk in any shell on any UNIX box:



$ awk 'printf "%s%s", (NR>1 ? "," : "["), $0 ENDprint "]"' file
[1,2,3,4,5]





share|improve this answer






























    0














    You can append all the lines into the pattern space first before performing substitutions:



    sed ':a;N;$!ba;s/n/,/g;s/^/[/;s/$/]/' file


    This outputs:



    [1,2,3,4,5]





    share|improve this answer























    • when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

      – Joshua Segal
      Mar 23 at 20:28











    • That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

      – blhsing
      Mar 24 at 2:53



















    0














    This might work for you (GNU sed):



    sed '1h;1!H;$!d;x;s/n/,/g;s/.*/[&]/' file


    Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.






    share|improve this answer






























      -1














      If you want the list using python, a simple implementation is



      with open('./num.txt') as f:
      num = [int(line) for line in f]





      share|improve this answer























      • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

        – Joshua Segal
        Mar 23 at 20:16











      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%2f55315216%2fhow-to-turn-text-file-into-python-list-form%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      With GNU sed for -z to read the whole file at once:



      sed -z 's/n/,/g; s/^/[/; s/,$/]n/' file
      [1,2,3,4,5]


      With any awk in any shell on any UNIX box:



      $ awk 'printf "%s%s", (NR>1 ? "," : "["), $0 ENDprint "]"' file
      [1,2,3,4,5]





      share|improve this answer



























        1














        With GNU sed for -z to read the whole file at once:



        sed -z 's/n/,/g; s/^/[/; s/,$/]n/' file
        [1,2,3,4,5]


        With any awk in any shell on any UNIX box:



        $ awk 'printf "%s%s", (NR>1 ? "," : "["), $0 ENDprint "]"' file
        [1,2,3,4,5]





        share|improve this answer

























          1












          1








          1







          With GNU sed for -z to read the whole file at once:



          sed -z 's/n/,/g; s/^/[/; s/,$/]n/' file
          [1,2,3,4,5]


          With any awk in any shell on any UNIX box:



          $ awk 'printf "%s%s", (NR>1 ? "," : "["), $0 ENDprint "]"' file
          [1,2,3,4,5]





          share|improve this answer













          With GNU sed for -z to read the whole file at once:



          sed -z 's/n/,/g; s/^/[/; s/,$/]n/' file
          [1,2,3,4,5]


          With any awk in any shell on any UNIX box:



          $ awk 'printf "%s%s", (NR>1 ? "," : "["), $0 ENDprint "]"' file
          [1,2,3,4,5]






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 13:50









          Ed MortonEd Morton

          118k1345105




          118k1345105























              0














              You can append all the lines into the pattern space first before performing substitutions:



              sed ':a;N;$!ba;s/n/,/g;s/^/[/;s/$/]/' file


              This outputs:



              [1,2,3,4,5]





              share|improve this answer























              • when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

                – Joshua Segal
                Mar 23 at 20:28











              • That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

                – blhsing
                Mar 24 at 2:53
















              0














              You can append all the lines into the pattern space first before performing substitutions:



              sed ':a;N;$!ba;s/n/,/g;s/^/[/;s/$/]/' file


              This outputs:



              [1,2,3,4,5]





              share|improve this answer























              • when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

                – Joshua Segal
                Mar 23 at 20:28











              • That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

                – blhsing
                Mar 24 at 2:53














              0












              0








              0







              You can append all the lines into the pattern space first before performing substitutions:



              sed ':a;N;$!ba;s/n/,/g;s/^/[/;s/$/]/' file


              This outputs:



              [1,2,3,4,5]





              share|improve this answer













              You can append all the lines into the pattern space first before performing substitutions:



              sed ':a;N;$!ba;s/n/,/g;s/^/[/;s/$/]/' file


              This outputs:



              [1,2,3,4,5]






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 23 at 15:37









              blhsingblhsing

              46.8k51747




              46.8k51747












              • when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

                – Joshua Segal
                Mar 23 at 20:28











              • That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

                – blhsing
                Mar 24 at 2:53


















              • when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

                – Joshua Segal
                Mar 23 at 20:28











              • That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

                – blhsing
                Mar 24 at 2:53

















              when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

              – Joshua Segal
              Mar 23 at 20:28





              when I do seq 5 | sed -z 's/^/[/; s/n/,/g; s/,?$/]n/' it seems to not even change the output. It's identical to seq 5

              – Joshua Segal
              Mar 23 at 20:28













              That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

              – blhsing
              Mar 24 at 2:53






              That isn't my code (that is oguzismail's code). Please run the demo here: tio.run/##K05N0U3PK/3/3yrR2s9aRTEp0bpYPyZPX0c/…

              – blhsing
              Mar 24 at 2:53












              0














              This might work for you (GNU sed):



              sed '1h;1!H;$!d;x;s/n/,/g;s/.*/[&]/' file


              Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.






              share|improve this answer



























                0














                This might work for you (GNU sed):



                sed '1h;1!H;$!d;x;s/n/,/g;s/.*/[&]/' file


                Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.






                share|improve this answer

























                  0












                  0








                  0







                  This might work for you (GNU sed):



                  sed '1h;1!H;$!d;x;s/n/,/g;s/.*/[&]/' file


                  Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.






                  share|improve this answer













                  This might work for you (GNU sed):



                  sed '1h;1!H;$!d;x;s/n/,/g;s/.*/[&]/' file


                  Copy the first line to the hold space, append copies of subsequent lines and delete the originals. At the end of the file, swap to the hold space, replace newlines by commas, and surround the remaining string by square brackets.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 9:48









                  potongpotong

                  37.2k43063




                  37.2k43063





















                      -1














                      If you want the list using python, a simple implementation is



                      with open('./num.txt') as f:
                      num = [int(line) for line in f]





                      share|improve this answer























                      • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                        – Joshua Segal
                        Mar 23 at 20:16















                      -1














                      If you want the list using python, a simple implementation is



                      with open('./num.txt') as f:
                      num = [int(line) for line in f]





                      share|improve this answer























                      • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                        – Joshua Segal
                        Mar 23 at 20:16













                      -1












                      -1








                      -1







                      If you want the list using python, a simple implementation is



                      with open('./num.txt') as f:
                      num = [int(line) for line in f]





                      share|improve this answer













                      If you want the list using python, a simple implementation is



                      with open('./num.txt') as f:
                      num = [int(line) for line in f]






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 23 at 15:26









                      MerigMerig

                      830410




                      830410












                      • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                        – Joshua Segal
                        Mar 23 at 20:16

















                      • Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                        – Joshua Segal
                        Mar 23 at 20:16
















                      Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                      – Joshua Segal
                      Mar 23 at 20:16





                      Thanks. I probably should have added that this is supposed to be more of a sed exercise, but thanks for the code snippet

                      – Joshua Segal
                      Mar 23 at 20:16

















                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55315216%2fhow-to-turn-text-file-into-python-list-form%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

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript