2010-12-10 83 views
0

你好我有以下代碼:eval函數在Python

PATH =您的硬盤

def K(path): 
    try: 

     getfile = open(path + '/test.txt') 
     line = getfile.readlines() 
     print line 
     getfile.close() 

    except: 
     line = getfile.readlines() 
     eval(line) 
     d = dict() 
     val= d[k] 

一些目的地導入文本文件,我現在的問題是避免\n,我假定可以使用eval()函數完成。我想字符串,我得到的輸入轉換,以花車,我可以..

感謝名單適用於任何提示提前

+1

如果你描述你的文本文件的格式,這將有所幫助。使用'eval'來避免'\ n'是無法描述的。 – khachik 2010-12-10 09:43:08

+0

這段代碼應該做什麼? – 2010-12-10 09:43:36

+0

它在我的硬盤上需要一些file.txt文件,並將文本作爲字符串導入到python shell,所以如果立即文件有1,2(newline)2,3(newline)7,5,我在shell中獲得的輸入是['1,2 \ n','2,3 \ n','7,5'],我希望它能成爲我可以使用的數字:)希望能夠幫助 – user457142 2010-12-10 09:47:53

回答

1

我不會評論你的代碼,只會發佈一個例子,你可以檢查和修改,以使其工作。該函數讀取文本文件的內容並將由空格分隔的標記爲浮點數如果可能的話:

def getFloats(filepath): 
    fd = open(filepath) # open the file 
    try: 
    content = fd.read().split() # read fully 
    def flo(value): # a function that returns a float for the given str or None 
     try: return float(value) 
     except ValueError: return None # skip invalid values 
    # iterate through content and make items float or None, 
    # iterate over the result to choose floats only 
    return [x for x in [flo(y) for y in content] if x] 
    finally: 
    fd.close() 
1

你的代碼是相當混亂......讀取包含每行一個浮子上的文件,你可以簡單地做:

val = map(float, open("test.txt")) 

val將包含您的數據。每一個元素是一個浮動

01名單
+0

'val = [float(line)for open in line('test.txt')]'會更清晰和更具有內存效率(因爲迭代文件中的行不會一次讀取所有行,不像'readlines方法()')。 – 2010-12-10 14:41:26

+0

@benhoyt:你是對的......當我需要同時播放多條線時,我經常最終使用'L = open(xxx).readlines()',這是危險地到達手指級別的東西現在。 – 6502 2010-12-10 15:26:25

0

ast.literal_eval()會變成每一行成元組,然後可以遍歷或索引值。

0

這是一個函數read_numbers(),它返回浮點列表的列表。

def read_numbers(filename): 
    numbers = [] 
    with open(filename) as f: 
     for line in f: 
      lst = [float(word) for word in line.split(',')] 
      numbers.append(lst) 
    return numbers 

如果文件包含:

1, 2 
2, 3 
7, 5 

然後read_numbers('filename')將返回:

[[1.0, 2.0], [2.0, 3.0], [7.0, 5.0]] 

你可能想要做的錯誤處理(或簡單地忽略錯誤),擴大了內部列表理解並打電話給float()try ... except ValueError