Read in parameters with links from textfile I'm trying to read in a few lines of parameters from an textfile and format these paths.

How can I improve this code to work with less lists? I just need the final paths.

import os
config = open("C:\\Users\\config.txt")
content = config.readlines()
removedEnds = []
removedStarts = []
finalPaths = []

for string in content:
    removedEnds.append(string.rstrip())

for string in removedEnds:
    print(string)
    if string.find('='):
        removedStarts.append(string[(string.find('=')+1):])

for string in removedStarts:
    finalPaths.append(string.split("\\"))

for string in finalPaths:
    print(os.path.join(*string))


The textfile looks like this:

Source=C:\Users\workspace\OMDB\WebContent\app
Target=C:\Apache24\htdocs
Rather than creating a series of lists, you should just iterate over the lines of the file directly. You don't need to maintain state between any two lines &ndash; just process them as you get them.

A few idioms you should also note:


Use the with open(...) constructions. This ensures the file is always closed, even if the script throws an exception. (Your script never closes the file.)
Rather than using if string.find('='), use if '=' in string.
Rather than using string[(string.find('=')+1):] to get the portion after the equals sign, I think it's neater and more Pythonic to use string.split('=', maxsplit=1)[1]




Here's a version of the script that doesn't use any lists:

import os


with open('C:\\Users\\config.txt') as f:
    for line in f:
        if '=' in line:
            path = line.split('=', maxsplit=1)[1].strip()
            components = path.split('\\')
            print(os.path.join(*components))