2009-11-10 14 views
1

是有可能在Python,給出10000線,其中它們都具有此結構的文件:如何讀取,在一條線上,從列A中的所有字符爲B

1,2 xvfrt ert5a fsfs4 DF˚Ffdfd56,234

或類似的,讀取整個字符串,然後在另一個字符串從7列中的所有字符存儲到第17列,包括空格,因此新的字符串將是

「xvfrt ert5a 「?

非常感謝

回答

1

這在技術上回答直接的問題:

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

但有一個致命的缺陷。可以用一次性代碼,但數據看起來像逗號分隔值,第三個字段甚至可能是空間分隔的數據塊。遠不如像這樣做,這樣,如果前兩列發芽的額外的數字,它仍然可以工作:

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

如果這些空間分隔塊可能會更長,那麼這樣的:

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

不要忘記一兩條評論來解釋發生了什麼。也許:

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

當然,假設這些是許可證密鑰。評論中不需要太抽象。

0
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! 
5
another_list = [] 
for line in f: 
    another_list.append(line[6:17]) 

或發電機(記憶友好的解決方案):

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

其實應該是[6:17]。發電機版本+1! – ema 2009-11-10 18:45:17

+0

@ema,對!感謝您的更正 – 2009-11-10 18:47:11

1

你不說你想怎麼把數據從每個存儲10000行 - 如果你想要他們在列表中,你會做這樣的事情:

my_list = [] 

for line in open(filename): 
    my_list.append(line[7:18]) 
7
lst = [line[6:17] for line in open(fname)] 
0

這functionw將計算所需的字符串,並把它打印出來

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

我打算把邁克爾狄龍的答案稍微提一點。如果「第6列至第17列」表示「第三個逗號分隔字段的前11個字符」,則這是使用csv模塊的好機會。另外,對於Python 2.6及更高版本,打開文件時使用'with'語句被認爲是最佳實踐。看:

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

這將保留領先的空白;如果你不想這樣,最後一行改爲

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