PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to save multiple lines of a txt file as one string, starting and stopping at certain keywords

 May 13, 2022     append, list, python     No comments   

Issue

I have a stored procedure stored as a .txt file. I am trying to store all of the "joins" to a file. I know how to isolate some of the joins by breaking the txt file into lines and reading them:

mylist[]
for line in lines:
     if line.startswith('inner'):
          mylist.append({'join': line})
      

However, the issue comes in where some of the joins are not on one line. For example:

inner join tablea a
  on tableb.id = a.id

inner join tablec c
  on tabled.id = c.id

left outer join tabled d
  on tablee.id = d.id

Is it possible to join multiple lines (all lines after the first keyword 'inner' and before the next keyword 'inner') to one string? Making something that looks like this:

inner join tablea a on tableb.id = a.id
inner join tablec c on tabled.id = c.id
left outer join tabled d on tablee.id = d.id
etc

My, admittedly novice, thinking on this would be to search the txt file for lines that begin with keywords like 'on' and then append that line to the line above it. From there, I can just extract all lines that start with either 'inner' or left'.


Solution

This works:

a = open("./textFile")

lines = a.readlines()

L = []
for i in range(len(lines)):
     if lines[i].startswith('inner'):
          temp = i + 1
          toAdd = lines[i]
          while not lines[temp].startswith("inner") and temp < len(lines)-1:
               toAdd += lines[temp]

               temp+=1

          toAdd = toAdd.replace("\n", "")
          L.append({'join': toAdd})

print(L)


Answered By - Braden Yonano
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing