-1

I am currently trying to create a python program that prints out specific sections of a file. I tried using file.read() and file.readline() but I can't seem to get an exact position, just either full lines or bits. Is there a better function to be using or an import I can use?

The problem I am running into is my files output reads

facet normal 0.00000e+00 0.00000e+00 0.00000e+00

I want to take the values and put them into a variable. I would like to create an if statement that takes those three values and adds them to different variables however I don't know of a function that does that. Should I be trying to parse the file first?

My code to provide the output is

f = open ('/pycharm/sphere.stl')
for line in f:
  print(line)

I would like to have an if statement along the lines of

f = open ('/pycharm/sphere.stl')
for line in f:
  if line == "facet normal"
    a = nextFloat()
    if a == true
      b = nextFloat()
      if b == true
        c = nextFloat()
      if c == true
        d = a + b + c
        print (d)

I am trying to solve for d but I can't find a way to use the output of the file in order to input for d.

  • Please give us your file example. – McGrady Mar 30 '17 at 02:28
  • You mean , to read specific lines of a file.? – Suresh Mar 30 '17 at 02:33
  • Possible duplicate of [Python - How can I open a file and specify the offset in bytes?](http://stackoverflow.com/questions/3299213/python-how-can-i-open-a-file-and-specify-the-offset-in-bytes) – Chris Martin Mar 30 '17 at 02:35
  • It all kinda depends on the format of the file. What are "sections"? How do you know where they are. You'll get a lot further here if you have sample data, a description of the file format and your attempt at getting it to work. – tdelaney Mar 30 '17 at 02:41
  • Read https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files to get an overview of Python file read/write primitives. If nothing fits your needs, read all the file content and search inside it to identify the "section" you are talking about. – Julien V Mar 30 '17 at 13:07
  • What you have tried so far? Provide some code samples, input and output examples. – Dmitry Shilyaev Apr 03 '17 at 20:38

1 Answers1

-1

I think what you are looking for is something like regular expressions. However you can in principle do something like split:

for line in f.readlines():
  if line.split()[0] == 'fact normal':
    a = nextFloat() ## the rest of your code...

hope that helps you.

Chris
  • 710
  • 7
  • 15