0

I'm trying to print multiple lines (in this case 2 lines) from a *.txt file with Python.

I want to print both "if" in the same line but I can't.

Code:

import os
import sys

path = #sys.argv[1]
InputText1 = '#  Class ID     Number of Cells    Class Name'
InputText2 = '# Means'


for file in os.listdir(path):
    #print file [13:15]
    #if file.endswith("*.gsg"):
        #print os.path.join(path,file)
    with open(os.path.join(path,file), "r") as input:
        for line in input:
            if InputText1 in line:
                #print(line)
                print str(file)[0:1].strip() + "," + str(next(input)[:10].strip()) + ","
            if InputText2 in line:
                #print(line)
                print next(input).strip()

Results:

1,1,
5.004188e-001
1,2,
5.822568e-001
1,3,
6.339202e-001
1,4,
6.711560e-001
1,5,
6.976744e-001
5
  • next(input) => next(input).rstrip() to remove linefeed from the line Commented Apr 25, 2018 at 16:19
  • or next(input).strip() to remove spaces & linefeed Commented Apr 25, 2018 at 16:21
  • Thanks, it works for the space problem but not for the new line problem, any suggestion? (I edit the question, code and results) Commented Apr 25, 2018 at 17:14
  • can you provide a sample or your input file? note that printing without linefeed is covered in many answers here as well. I have edited the duplicate links to add: stackoverflow.com/questions/493386/… Commented Apr 25, 2018 at 19:34
  • I all ready have already solved it. I will put the new code down the old one. Commented Apr 27, 2018 at 22:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.