English 中文(简体)
How to read, in a line, all characters from column A to B
原标题:

is it possible in Python, given a file with 10000 lines, where all of them have this structure:

1, 2, xvfrt ert5a fsfs4 df f fdfd56 , 234

or similar, to read the whole string, and then to store in another string all characters from column 7 to column 17, including spaces, so the new string would be

"xvfrt ert5a" ?

Thanks a lot

最佳回答

This technically answers the direct question:

lst = [line[6:17] for line in open(fname)]

but there is a fatal flaw. It is OK for throwaway code, but that data looks suspiciously like comma separated values, and the third field may even be space delimited chunks of data. Far better to do it like this so that if the first two columns sprout an extra digit, it will still work:

lst = [x[2].strip()[0:11] for x in [line.split( , ) for line in open(fname)]]

And if those space delimited chunks might get longer, then this:

lst = [x[2].strip().split()[0:2] for x in [line.split( , ) for line in open(fname)]]

Don t forget a comment or two to explain what is going on. Perhaps:

# on each line, get the 3rd comma-delimited field and break out the 
# first two space-separated chunks of the licence key

Assuming, of course, that those are licence keys. No need to be too abstract in comments.

问题回答
lst = [line[6:17] for line in open(fname)]
another_list = []
for line in f:
    another_list.append(line[6:17])

Or as a generator (a memory friendly solution):

another_list = (line[6:17] for line in f)

I m going to take Michael Dillon s answer a little further. If by "columns 6 through 17" you mean "the first 11 characters of the third comma-separated field", this is a good opportunity to use the csv module. Also, for Python 2.6 and above it s considered best practice to use the with statement when opening files. Behold:

import csv
with open(filepath,  rt ) as f:
  lst = [row[2][:11] for row in csv.reader(f)]

This will preserve leading whitespace; if you don t want that, change the last line to

  lst = [row[2].lstrip()[:11] for row in csv.reader(f)]

You don t say how you want to store the data from each of the 10,000 lines -- if you want them in a list, you would do something like this:

my_list = []

for line in open(filename):
    my_list.append(line[7:18])
for l in open("myfile.txt"):
   c7_17 = l[6:17]
   # Not sure what you want to do with c7_17 here, but go for it!

This functionw will compute the string that you want and print it out

def readCols(filepath):
    f = open(filepath,  r )
        for line in file:
            newString = line[6:17]
            print newString




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签