How to combine every line with it's subsequent line in a text fileText File Parsing with PythonRelative imports for the billionth timebs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?Combine multiple lines of text documents into oneMerging every two lines in a text file - PythonHow to lowercase a portion of text using pythonPython line.replace in a text file is adding unwanted blank linesIn python insert one space after every 5th Character in each line of a text filetrouble writting to text file and maintaining format pythonPython 2.7 read each line in text file until character

How do people drown while wearing a life jacket?

Custom Metadata SOQL WHERE clause not working

Is it uncompelling to continue the story with lower stakes?

C# TCP server/client class

Write The Shortest Program to Calculate Height of a Binary Tree

Javascript - Find a deepest node in a binary tree

what can you do with Format View

How can I use commands with sudo without changing owner of the files?

Can a Hogwarts student refuse the Sorting Hat's decision?

Are valid inequalities worth the effort given modern solver preprocessing options?

What percentage of campground outlets are GFCI or RCD protected?

What is the right Bonferroni adjustment?

Getting an entry level IT position later in life

How to design an effective polearm-bow hybrid?

3 beeps on a 486 computer with an American Megatrends bios?

Piece de Resistance - Introduction & Ace and A's

When using the Proficiency Dice optional rule, how should they be used in determining a character's Spell Save DC?

Is the first page of a novel really that important?

Why is it to say 'paucis post diebus'?

Broken bottom bracket?

Is a switch from R to Python worth it?

If someone else uploads my GPL'd code to Github without my permission, is that a copyright violation?

Need reasons why a satellite network would not work

How to call made-up data?



How to combine every line with it's subsequent line in a text file


Text File Parsing with PythonRelative imports for the billionth timebs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?Combine multiple lines of text documents into oneMerging every two lines in a text file - PythonHow to lowercase a portion of text using pythonPython line.replace in a text file is adding unwanted blank linesIn python insert one space after every 5th Character in each line of a text filetrouble writting to text file and maintaining format pythonPython 2.7 read each line in text file until character






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have a text file z.txt. It looks like this:



alcoholic
alert
algebra
alibi
blablabla
...


How can I use python to make each line look like this (combined with it's subsequent line):



alcoholic alert
alert algebra
algebra alibi
alibi blablabla
blablabla ...


The incomplete code I have looks like this:



with open('z.txt','r') as inF:
for line in inF:
line =


Any help would be appreciated. Thanks.










share|improve this question
































    1















    I have a text file z.txt. It looks like this:



    alcoholic
    alert
    algebra
    alibi
    blablabla
    ...


    How can I use python to make each line look like this (combined with it's subsequent line):



    alcoholic alert
    alert algebra
    algebra alibi
    alibi blablabla
    blablabla ...


    The incomplete code I have looks like this:



    with open('z.txt','r') as inF:
    for line in inF:
    line =


    Any help would be appreciated. Thanks.










    share|improve this question




























      1












      1








      1


      1






      I have a text file z.txt. It looks like this:



      alcoholic
      alert
      algebra
      alibi
      blablabla
      ...


      How can I use python to make each line look like this (combined with it's subsequent line):



      alcoholic alert
      alert algebra
      algebra alibi
      alibi blablabla
      blablabla ...


      The incomplete code I have looks like this:



      with open('z.txt','r') as inF:
      for line in inF:
      line =


      Any help would be appreciated. Thanks.










      share|improve this question
















      I have a text file z.txt. It looks like this:



      alcoholic
      alert
      algebra
      alibi
      blablabla
      ...


      How can I use python to make each line look like this (combined with it's subsequent line):



      alcoholic alert
      alert algebra
      algebra alibi
      alibi blablabla
      blablabla ...


      The incomplete code I have looks like this:



      with open('z.txt','r') as inF:
      for line in inF:
      line =


      Any help would be appreciated. Thanks.







      python-2.7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 3:23







      Neal

















      asked Mar 27 at 2:44









      NealNeal

      155 bronze badges




      155 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          1














          I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.



          Let suppose your z.txt has the following contents in it.




          z.txt




          alcoholic
          alert
          algebra
          alibi
          blablabla


          Now, you can try like this.




          construct.py




          output_lines = []

          with open("z.txt") as f:
          lines = f.readlines()
          l = len(lines)

          if l <= 1:
          if l == 1:
          output_lines = lines[0]
          else:
          # strip() is to remove `n` from end of `lines[index]`
          output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

          print(output_lines)
          # ['alcoholic alertn', 'alert algebran', 'algebra alibin', 'alibi blablabla']

          # If you wish to save it in a file named `z_out.txt`
          with open("z_out.txt", "w") as f:
          f.writelines(output_lines)



          z_out.txt




          alcoholic alert
          alert algebra
          algebra alibi
          alibi blablabla





          share|improve this answer


































            1














            Here's a possibility using list comprehension, giving you the output in the form of a list.



            with open('z.txt','r') as f: 
            wordlist = f.read().split('n')

            >>>wordlist
            ['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

            combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

            >>>combineduo
            ['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']





            share|improve this answer



























              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%2f55369027%2fhow-to-combine-every-line-with-its-subsequent-line-in-a-text-file%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









              1














              I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.



              Let suppose your z.txt has the following contents in it.




              z.txt




              alcoholic
              alert
              algebra
              alibi
              blablabla


              Now, you can try like this.




              construct.py




              output_lines = []

              with open("z.txt") as f:
              lines = f.readlines()
              l = len(lines)

              if l <= 1:
              if l == 1:
              output_lines = lines[0]
              else:
              # strip() is to remove `n` from end of `lines[index]`
              output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

              print(output_lines)
              # ['alcoholic alertn', 'alert algebran', 'algebra alibin', 'alibi blablabla']

              # If you wish to save it in a file named `z_out.txt`
              with open("z_out.txt", "w") as f:
              f.writelines(output_lines)



              z_out.txt




              alcoholic alert
              alert algebra
              algebra alibi
              alibi blablabla





              share|improve this answer































                1














                I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.



                Let suppose your z.txt has the following contents in it.




                z.txt




                alcoholic
                alert
                algebra
                alibi
                blablabla


                Now, you can try like this.




                construct.py




                output_lines = []

                with open("z.txt") as f:
                lines = f.readlines()
                l = len(lines)

                if l <= 1:
                if l == 1:
                output_lines = lines[0]
                else:
                # strip() is to remove `n` from end of `lines[index]`
                output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

                print(output_lines)
                # ['alcoholic alertn', 'alert algebran', 'algebra alibin', 'alibi blablabla']

                # If you wish to save it in a file named `z_out.txt`
                with open("z_out.txt", "w") as f:
                f.writelines(output_lines)



                z_out.txt




                alcoholic alert
                alert algebra
                algebra alibi
                alibi blablabla





                share|improve this answer





























                  1












                  1








                  1







                  I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.



                  Let suppose your z.txt has the following contents in it.




                  z.txt




                  alcoholic
                  alert
                  algebra
                  alibi
                  blablabla


                  Now, you can try like this.




                  construct.py




                  output_lines = []

                  with open("z.txt") as f:
                  lines = f.readlines()
                  l = len(lines)

                  if l <= 1:
                  if l == 1:
                  output_lines = lines[0]
                  else:
                  # strip() is to remove `n` from end of `lines[index]`
                  output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

                  print(output_lines)
                  # ['alcoholic alertn', 'alert algebran', 'algebra alibin', 'alibi blablabla']

                  # If you wish to save it in a file named `z_out.txt`
                  with open("z_out.txt", "w") as f:
                  f.writelines(output_lines)



                  z_out.txt




                  alcoholic alert
                  alert algebra
                  algebra alibi
                  alibi blablabla





                  share|improve this answer















                  I am going to construct a list containing the lines of the desired output. Finally, I'll write those lines to a file named z_out.txt.



                  Let suppose your z.txt has the following contents in it.




                  z.txt




                  alcoholic
                  alert
                  algebra
                  alibi
                  blablabla


                  Now, you can try like this.




                  construct.py




                  output_lines = []

                  with open("z.txt") as f:
                  lines = f.readlines()
                  l = len(lines)

                  if l <= 1:
                  if l == 1:
                  output_lines = lines[0]
                  else:
                  # strip() is to remove `n` from end of `lines[index]`
                  output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

                  print(output_lines)
                  # ['alcoholic alertn', 'alert algebran', 'algebra alibin', 'alibi blablabla']

                  # If you wish to save it in a file named `z_out.txt`
                  with open("z_out.txt", "w") as f:
                  f.writelines(output_lines)



                  z_out.txt




                  alcoholic alert
                  alert algebra
                  algebra alibi
                  alibi blablabla






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 27 at 3:39

























                  answered Mar 27 at 3:00









                  hygullhygull

                  4,7732 gold badges17 silver badges32 bronze badges




                  4,7732 gold badges17 silver badges32 bronze badges


























                      1














                      Here's a possibility using list comprehension, giving you the output in the form of a list.



                      with open('z.txt','r') as f: 
                      wordlist = f.read().split('n')

                      >>>wordlist
                      ['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

                      combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

                      >>>combineduo
                      ['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']





                      share|improve this answer





























                        1














                        Here's a possibility using list comprehension, giving you the output in the form of a list.



                        with open('z.txt','r') as f: 
                        wordlist = f.read().split('n')

                        >>>wordlist
                        ['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

                        combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

                        >>>combineduo
                        ['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']





                        share|improve this answer



























                          1












                          1








                          1







                          Here's a possibility using list comprehension, giving you the output in the form of a list.



                          with open('z.txt','r') as f: 
                          wordlist = f.read().split('n')

                          >>>wordlist
                          ['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

                          combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

                          >>>combineduo
                          ['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']





                          share|improve this answer













                          Here's a possibility using list comprehension, giving you the output in the form of a list.



                          with open('z.txt','r') as f: 
                          wordlist = f.read().split('n')

                          >>>wordlist
                          ['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

                          combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

                          >>>combineduo
                          ['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 27 at 3:19









                          kerweikerwei

                          1,5341 gold badge9 silver badges20 bronze badges




                          1,5341 gold badge9 silver badges20 bronze badges






























                              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%2f55369027%2fhow-to-combine-every-line-with-its-subsequent-line-in-a-text-file%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

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현