2012-11-30 27 views
0

首先,對於這個簡單的問題抱歉。我知道這些問題是非常基本的。我需要在Python 2.7中保存一個包含多行的txt文件。我需要提出一些建議來改進我的基本代碼。在Python中保存一個txt文件,一些提示改善我的代碼

這是一個基本的例子

file_out = open("..//example//test.text", "w") 

for p in range(10): 
    ID = str(p) 
    A = p*10 
    B = p+10 
    C = p-10 
    D = p+p 
    E = p*2 
    file_out.write("s% %s %s %s s% s%" % (ID,A,B,C,D,E)+ "\n") 
file_out.close() 

我的問題是:

  • 我有這樣的錯誤信息,我did'n找到一個方法來解決

    Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
        ValueError: incomplete format 
    
  • 我要保存的元素(例如:ID,A,B,C,D,E)是幾個(30個元素),而我使用了一個long s的%行。有沒有一個優雅的方式和緊湊的代碼 這條線?。

  • 我也想保存一個頭(例如:ID,A,B,C,D,E)。 要做到這一點的最佳途徑是什麼?

回答

1

你有一個錯字

file_out.write("%s %s %s %s %s %s" % (ID,A,B,C,D,E)+ "\n") 

file_out.write("%s %s %s %s %s %s\n" % (ID,A,B,C,D,E)) 

file_out.write(" ".join(["%s" %i for i in [A, B, C, D, E]])) 
+0

謝謝。我不明白我怎麼可以創建一個標題(我的txt文件的第一行( –

3

ValueError: incomplete format

你寫的%s格式的一半s%。百分號首先出現。

my element to save (ex: ID,A,B,C,D,E) are several (30 elements), and i use a long line of s%. IS there an elegant way and compact to code this line?.

' '.join(str(x) for x in [p, p*10, p+10, p-10, p+p, p*2]) 
+0

@johan thanks。爲了保存頭文件,我需要在''.join(str(x)for x [p,p * 10,p + 10,p-10,p + p,p * 2])之前輸入一個新行。 –

1

%第一,然後的說明符。

%s 

另外:

print >>file_out, ' '.join(...) 

此外,csv

1

你有幾個語法錯誤。檢查你的格式化字符串。

file_out = open("..//example//test.text", "w") 

for p in range(10): 
    ID = str(p) 
    A = p*10 
    B = p+10 
    C = p-10 
    D = p+p 
    E = p*2 
    file_out.write("%s %s %s %s %s %s" % (ID,A,B,C,D,E) + "\n") 
file_out.close() 
相關問題