Hello guys, I am new around here. Anyways, I am having a problem with reading some information from a text file.

Sample text file:

density = -1.0
number = 2004


Ok so what do I use in order to get the number -1.0 from the text file? Also, what if I have to get the number 2004 (To move on to the next line....). The code I have been using works, but it returns to me the whole second line, when I only want the number 2004 (I used the linecache module and it returns the whole text in the second line). That is just a random text file, but say all my text files have the SAME format but the numbers change....how do i tell python to grab the full number?

Recommended Answers

All 9 Replies

This should do it. You must set x to the line that the info is on

file = open('myfile.txt', 'r')
x = 2
while x:
	line = file.readline()
	x -= 1
words = line.split()
index = words.index('=')
num = words[index+1]
fin_num = int(num)
print fin_num
file.close()

if i understand your problem correctly i think is what you want,

for line in open('myfile.txt','rb'):
    numbers = line.strip().split('=')[1]
    print numbers

Baki is right. Iterate the lines and split them at the equals sign (but strip it properly!), then take the latter index (the right side of the sign). Strip off the leading and trailing whitespace (of each index), and voila. Here's if you wanted to make sure that the left-side was "number":

for line in open('myfile.txt','r').readlines():
    # split at = and then strip whitespace from both sides
    data = [x.strip() for x in line.split('=')]
    if data[0] == 'number':
        number = data[1]

The list comprehension I used strips each index that it gets from splitting at the equals sign. Baki's way would strip the beginning and end of whitespace. But when it's split, you'd get a space left before and after the indices, so I stripped that off.

thanks for picking that up but you can also swap the split() & strip(). so you split to get the intended result and then strip whatever whitespaces is still left

You can't just swap them - strip() is for strings and after you've called split(), you have a list. If you swap them in order you'll get an error. Hence splitting, then cycling the indices to strip() each one in that list comprehension. As shown:

>>> a = "hello world!"
>>> a.split(" ").strip()

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a.split(" ").strip()
AttributeError: 'list' object has no attribute 'strip'

shadwickman is right,
data = [x.strip() for x in line.split('=')]
works because x inside the list comprehension is still a string and not a list yet.

You might want to convert the numeric strings to actual numbers you can do calculations with using int() or float(). Here is my dime's worth:

mydata = """\
density = -1.0
number = 2004
"""

# write a test data file
fout = open("mydata.txt", "w")
fout.write(mydata)
fout.close()

for line in file("mydata.txt"):
    data = [x.strip() for x in line.split('=')]
    if 'density' in data:
        density = float(data[1])
    if 'number' in data:
        # if it's always a whole number use int()
        number = int(data[1])

# test
print(density)  # -1.0
print(number)   # 2004

shadwick and baki, I tried your method and I printed out to see what it would give me back. This is what prints out:


I actually wanted to just store the number 2004 onto some variable. Sorry for not being too clear. What I'm trying to do is read numbers from an output file created by a program and then get those numbers with python then pass them back to another program that will generate some plots and such....if that makes sense. The output files all have the same format, though the numbers change depending on the inputs that are put into the program that generates the results. Is there any way in which I can just be setting the line for python to move to and then obtain the number?

Thanks for the help :)

Ene Uran, your method works!. Thank you so much to all for the help, I really appreciate it!!

You could try this approach:

def extract_number(data_str):
    """
    extract the numeric value from a string
    the string should contain only one number
    return the number string
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    return s

mydata = """\
density = -1.0
number = 2004
"""

# write a test data file
fout = open("my_data.txt", "w")
fout.write(mydata)
fout.close()

newdata = ""
for line in file("my_data.txt"):
    newdata += extract_number(line) + '\n'

# test
print(newdata)

# write the new data file
fout = open("my_numbers.txt", "w")
fout.write(newdata)
fout.close()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.