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
任何幫助表示讚賞。
我不得不改變在all_line [:]範圍內+1,因爲它不打印最後一行,否則它的驚人。非常感謝 ;) – gogo 2014-12-05 12:45:03