-1

Using Python 3.x how can I assign specific variables as strings from a notepad example:

Client number 00001

Client account 1-548

Client name Bob

Without doing this manually I want to get: file_name that contains

a=”00001”
b=”1-548”
c=”Bob”    

then import this to a script where i have different template's

I am looking to exchange 7 copy paste cycles into 1 / 2

from file_name import *
mail_temp1 = "text block %s text block %s text block %s text block" % (a, b, c)
mail_temp2 = "text block %s text block %s text block %s text block" % (a, d, e)

print(mail_temp1)
print(mail_temp2)    

Very new to programming. Thank you

  • I'm not sure if I understood it... Is "file_name" a Python file containing variable? – FBidu May 11 '19 at 20:12
  • `”` should be `"` .. beside that I have no clue what you are aiming for. There are tons of examples on SO for loading data from files into lists and you can feed the list instead of a tuple. Your formatting suggest 2.7 btw - 3.6 propagates `.format()` or `f-strings`: https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – Patrick Artner May 11 '19 at 20:16

1 Answers1

1

Let's assume you have a file called "file_name.txt" with the following contents:

Client number 00001
Client account 1-548
Client name Bob

One way you can extract the relevant information is by looping through every line of the file and saving only those that satisfies a specific condition. In the simplest case, something like this would be an example:

for line in open( 'file_name.txt', 'r' ):
    if line.startswith( 'Client number' ):
        a = line.split()[-1]
    if line.startswith( 'Client account' ):
        b = line.split()[-1]
    if line.startswith( 'Client name' ):
        c = line.split()[-1]

The for line in open() tells the code to loop through every line and store each line in the line variable. For each line variable, the code checks if it starts with a specific string via the str.startswith() function for strings. If it does satisfy this condition, the code splits the line by spaces and selects the last item of the list with the list[-1] notation.

Again, this is a simple example for a very specific example. Other things to consider is the case of the string, what you want to do when there are multiple instances of the same types of lines, what to do if specific lines are not present, etc.

Jason K Lai
  • 1,500
  • 5
  • 15