Domanda

I have a file that looks like

 12 MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
  8 O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

and I want to separate out the numbers from the front of the line, with an output of

MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

I have this

for line in file:
    head, sep, tail = line.partition('wildcard')
    print tail

What should I put in for the wildcard?

È stato utile?

Soluzione 2

You can use,

head, sep, tail = line.strip().partition(" ")

The whole program becomes like this

with open("Input.txt") as inFile:
    for line in inFile:
        print line.strip().partition(" ")[2]

Output

MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

Altri suggerimenti

Your format looks like a fixed-column format, where each column is of a fixed width.

If so, use slicing instead:

for line in file:
    print line[4:]

to slice off the first 4 characters.

Alternatively, split on whitespace once, with the None argument to str.split():

for line in file:
    tail = line.split(None, 1)[-1]
    print tail

str.split(None) skips whitespace at the start of the string and splits on the first sequence of whitespace characters after the first column. [-1] takes the last element; even if there is no more than one column on the line you'll get a result.

Demo:

>>> line = ' 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n'
>>> line.split(None, 1)
['16', 'S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n']
text = '''12 MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
  8 O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01'''


for line in text.splitlines():
    print line.split(None,1)[1]

result

MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01

Instead of doing it yourself, you could also use a library: NumPy's I/O routines (loadtxt) are very useful for parsing such files.

In your case, you'd have to specifiy a record data type (dtype parameter, see numpy.loadtxt).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top