2014-12-05 23 views
0
abcd 
1234.984 
5.2 1.33 0.00 
0.00 2.00 1.92 
0.00 1.22 1.22 
1 1 1 
asdf 
1.512 1.11 1.50 
0 0 0 
0 0 1.512 

假設我在上面的文件名爲x(每行之間沒有空行)。我想要做的是讀取每行,並將每個值(由多個空格分隔)存儲在某行中的某個變量中。稍後我想打印(每個浮點值)/2.12在文件中的相同位置。修改文件的特定行上的值

我在做以下工作,但我覺得我已經完全沒有了。我正在嘗試讀取每一行並使用strip()。split()來獲取每個值。但我無法得到它。

f1=open("x","r") 
f2=open("y","w") 

for i, line in enumerate(f1): 
    # for line 0 and 1, i wanted to print the lines as such 
    for i in range(0,1):   
     print >> f2, i 

    # from lines 2 to 4 i tried reading each value in each line and store it in a,b,c and finally print 
    for i in range(2,4):   
     l=line.strip().split() 
     a=l[0] 
     b=l[1] 
     c=l[2] 

     print >> f2, a, b, c 

    if i == 5: 
     l=line.strip().split() 

     # I want to store the value (of 1 + 1 + 1), don't know how 
     t=l[0]     

     print >> f2, t 

    if i == 6: 
     print >> f2, i 

    for i in range(7,t):  # not sure if i can use variable in range 
     l=line.strip().split() 
     a=l[0] 
     b=l[1] 
     c=l[2] 

     print >> f2, a, b, c 

任何幫助表示讚賞。

回答

1

其diffult理解你正在努力實現的到底是什麼,但如果我的猜測是正確的,你可以像這樣(我只寫讀輸入片):

all_lines = [] 

# first read all lines in a file (I assume file its not too big to do it) 
with open('data.csv', 'r') as f: 
    all_lines = [l.rstrip() for l in f.readlines()] 

# then process specific lines as you need. 
for l in all_lines[2:4]: 
    a,b,c = map(float, l.split()) 
    print(a,b,c) 
    # or save the values in other file 

t = sum(map(float,all_lines[5].split())) 
print(t) 

for l in all_lines[7:7+t]: 
    a,b,c = map(float, l.split()) 
    print(a,b,c) 
    # or save the values in other file 
+0

我不得不改變在all_line [:]範圍內+1,因爲它不打印最後一行,否則它的驚人。非常感謝 ;) – gogo 2014-12-05 12:45:03

相關問題