1

Let say there is a sample text file in Linux

[SampleText.txt]

1234 = 1234

abcd = 1234

efgh = /home/user/targetfile1.txt

ijkl = /home/user/targetfile2.txt

How I can get the specific path (/home/user/targetfile1.txt & /home/user/targetfile2.txt) out from the SampleText.txt and place it in a variable?

4
  • Are you asking how to read a file in Python? Please ask a more specific question, since this appears to be simply open("sampleText.txt","r").read(). What part of reading a file is confusing? Or are you asking about finding the file name in a line of data? If so, what are the actual formatting rules for the line of data? It would help us if you could post the code you've written so far, so we know what part confuses you. Commented Oct 7, 2011 at 3:22
  • No, that no what I means Commented Oct 7, 2011 at 3:23
  • I am able to read but how can I filter to get the filepath in the text file Commented Oct 7, 2011 at 3:24
  • "that no what I means". Okay. Please update the question to say what you actually mean. What part of reading a file is confusing to you? Please try to be very specific about your problem. We can't guess. Please do not add comments. Please update the question. Commented Oct 7, 2011 at 3:24

2 Answers 2

1

My suggested approach is to parse the file as a general configuration file, and store things that look like assignments. If you have other weird stuff going on in your file, this may not work, but I think it will work here.

myvars = {}

# iterate through all the lines
for line in open('SampleText.txt').readlines():
    # skip this line if it doesn't look like an assignment
    if not '=' in line: continue

    # split it into left and right pieces
    left, right = line.split('=', 1)

    # keep it around in a dictionary
    myvars[left.strip()] = right.strip()

# now you can query it to get stuff:
myvars['efgh']   # returns /home/user/targetfile1.txt 
Sign up to request clarification or add additional context in comments.

Comments

1

You need the ConfigParser module:

http://docs.python.org/library/configparser.html

It parses files that look like this. Not knowing your exact situation, I can't be sure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.