Monday 23 December 2013

Print specific row from a file


File output.txt contains following records:

C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data1\data2\data3\subdir3\data-092309.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data1\data2\subdir2\data-643478.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data1\subdir1\data-4352435.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data10\subdir10\data-76532754.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data10\subdir10\subdir9\data-6327789928.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data5\data6\subdir6\data-467368.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data5\subdir5\data-231324.xml
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data7\subdir7\data-98765.xml
-> Done


User wants to print specific rows only. Follow the procedure below to do that:

>>>f = open('output.txt')
>>> lines = f.readlines()
>>> print(lines[2]) # prints 3rd row of the file
C:\Users\Tom\Documents\001 Career Stuff\Tests\QA_Engineer\ScriptTest\data1\subdir1\data-4352435.xml
>>>
>>> #Do this when output needs to be in quotation marks (+ without "\n")
>>> print(repr(lines[2].strip('\n'))) # repr() manages quotation marks
'C:\\Users\\Tom\\Documents\\001 Career Stuff\\Tests\\QA_Engineer\\ScriptTest\\data1\\subdir1\\data-4352435.xml'

Follow the link to see more:
http://stackoverflow.com/questions/2081836/reading-specific-lines-only-python