简体   繁体   English

修改文件特定行上的值

[英]Modify values on specific lines of a file

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

Suppose if I have the above in a file named x (no blank lines between each line). 假设我在名为x的文件中包含上述内容(每行之间没有空行)。 What I want to do is read each line and store each of the value (seperated by multiple spaces) in the line in certain variable. 我想做的是读取每一行,并将行中的每个值(由多个空格分隔)存储在特定变量中。 Later I want to print (each of the floating point values)/2.12 in the same position in the file. 稍后我要在文件中的相同位置打印(每个浮点值)/2.12。

I was doing the following, but I think I am completely off. 我正在执行以下操作,但是我认为我已经完全离开了。 I am trying to read each line and use the strip().split() to obtain each value. 我试图读取每一行,并使用strip()。split()获得每个值。 But I am not able to get it. 但是我无法得到它。

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

Any help is appreciated. 任何帮助表示赞赏。

Its diffult to understand exactly what you are trying to achieve, but if my guess is correct, you could something like this (I write only about reading the input tile): 很难准确地理解您要实现的目标,但是如果我的猜测是正确的,您可能会这样(我只写关于阅读输入图块的信息):

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   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM