修改文件特定行的值

时间:2014-12-05 02:10:35

标签: python

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 个答案:

答案 0 :(得分:1)

很难准确理解你想要实现的目标,但如果我的猜测是正确的,你可以这样(我只写有关读取输入磁贴):

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