Erna Piantari Erna Piantari - 1 month ago 6
Python Question

How to read specific data from txt file using python

Help me, I have an data.txt file. and i want to read the specific data in that file

112652447744
that is freespace data in directory C.
This is the content of my data.txt file:

Caption FreeSpace Size
C: 112652447744 146776518656
D: 295803727872 299962986496
E:
Z:

Answer

You can read each line (ignoring the first) and separate it by spaces to get each column. This way you could extract the size and free space for each partition:

contents = # here go the file contents
# split the text file into lines and ignore the first line
lines = contents.splitlines()[1:]
part_data = {}
for line in lines:
    columns = line.split()  # split the lines along the white space characters
    if len(columns) != 3:
        continue  # incomplete lines
    part_data[columns[0]] = (columns[1], columns[2])

That will give you the free space and size for every partition in the dictionary. To get your actual result it'd be:

part_data['C:'][0]

If you only want the second column and second row, ignoring the drive letter, you can reduce it to the following:

contents = # here go the file contents
second_line = contents.splitlines()[1]
second_column = second_line.split()[1]

There you go, but that requires that it always formatted the same. If the second line does not have three columns, it won't actually work and cause an IndexError most likely.

Note that a_string.split() removes all whitespace automatically, while a_string.split(' ') will also return the whitespace in it.

Comments