如何用Python中的其他值替换文件中的值

时间:2014-08-08 20:22:16

标签: python

我正在用Python编写一个程序,从value1中的一个表中搜索column1,如果它存在,请在表的同一行中替换value2 。该表具有以空格分隔的行和列的值。前三行文件包含文本,因此在我的代码中,我跳过前三行并从第一列的第一个元素中搜索。我已经在python中编写了代码(python中的初学者)。我正在使用replace函数将value2替换为新值。没有错误,但替换方法不起作用。该值未在文件中修改。我在stackoverflow中搜索了类似的问题并实现了它,但无法找到正确的输出。如果你可以帮助我,那将是非常有帮助的。提前致谢。

跳过前三个标题行...

0  2.00000E-01  2.00000E+00  1.00000E-01  1.00000E-01  0.00000E+00  1.00000E-01    5315.58609617651
5  8.61341E-02  9.32377E-01  1.03878E-01  9.66092E-02  0.00000E+00  1.31608E-01    4874.21137697405
10  9.01592E-02  1.01589E+00  1.02249E-01  1.16872E-01  0.00000E+00  1.37603E-01    4868.99427672864
14  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641
-1000000000  9.16065E-02  1.02727E+00  1.02914E-01  1.15918E-01  0.00000E+00  1.34975E-01    4868.85701581641
-1000000001  4.76910E-03  5.52689E-02  9.21654E-03  2.79153E-02  1.00000E+10  2.92135E-02   0.000000000000000E+000
-1000000004  0.00000E+00  0.00000E+00  3.20802E-01  3.40467E-01  0.00000E+00  3.67390E-01   0.000000000000000E+000
-1000000005  0.00000E+00  0.00000E+00  1.43648E-02  4.09956E-02  1.00000E+10  3.97582E-02   0.000000000000000E+000

我的代码:     #蟒蛇     导入系统     #打开文件foce.ext并阅读内容

iteration=[]
obj_value=[]
with open('ex_foce.ext','r+') as file:
#to skip first three lines and store the elements in 1st and 8th column in two arrays
    line1=file.readlines()[2:]

    for line in line1:
        if line:
            information=line.split()
            iteration.append(information[0])
            obj_value.append(information[7])
    print(line1)

    print(iteration)

    print(obj_value)
    pos=iteration.index('-1000000000')
    print(pos)
    #replacing value2 by 1.0
    obj_value[pos]=1.0
    print(obj_value[pos])
    old_value=obj_value[pos]
    line_number=pos
    x=line1[line_number]
    file.write(x.replace( str(old_value), "1.0" ))

file.close()

5 个答案:

答案 0 :(得分:0)

执行line1=file.readlines()[2:]时,"光标"移动到文件的末尾。然后你要求用更换后的值写一行,那么它是不是在文件的末尾复制而不是仅仅修改到位?也许你在写作之前错过file.seek(...)电话。

答案 1 :(得分:0)

如果我对问题的理解是正确的,您需要以下内容:

在通过评论澄清之后编辑1

Edit2,以保存初步信息

# ... define value1, value3 ...
with open('ex_foce.ext') as f:
    lines = f.readlines()
    prelims = '\n'.join(lines[ : 2])
    lines = lines[2: ]
toWrite = ''
for line in lines:
    if line.startswith(value1):
        toWrite += ' '.join(line.split()[ : -1]) + value3 + '\n'
    else:
        toWrite += line + '\n'
with open('ex_foce.ext', 'w') as f:
    f.write(prelims + '\n' + toWrite);

根据需要替换value1value3

希望这有帮助。

答案 2 :(得分:0)

干净的方法是;

  • 打开文件进行阅读
  • 阅读文件中的所有行。
  • 关闭文件
  • 以你想要的方式操作
  • 打开要写入的文件(这将截断文件)
  • 将更改的文件写回文件
  • 关闭文件

您可以打开文件进行读写,然后使用seek返回到开头。但如果新内容小于旧内容,则会在文件末尾留下垃圾。

答案 3 :(得分:0)

with open('ex_foce.ext','r+') as f:
    lines = f.readlines() # don't slice, we need to use all lines later
    for ind, line in enumerate(lines[3:]): # keep track of the index of each line using enumerate from line 4 to the end
        spl = line.split()
        if (spl[0]) == '-1000000000': # if we find value
            lines[ind] = line.replace(spl[7],"1.0") # replace line in lines at ind/index with updated value
    f.seek(0) # go back to start of file
    for line in lines: # write updated lines
        f.write(line)

答案 4 :(得分:-1)

我认为问题在于您希望使用r+开放模式进行读写。即使只更改文件中的一个字符,这是最好的方法(我已经写了数千个这样的字符):

f = open("ex_foce.ext","r")        # original file for reading
g = open("ex_foce_mod.ext","w")    # "output", modified file
for _ in range(3):
    g.write(f.readline())          # copy header lines
for line in f:
    L = line.strip().split()
    if L[0]=='-1000000000': L[7] = '1.0'
    g.write(' '.join(L)+'\n')
f.close()
g.close()

这将

  1. 如果程序失败,请避免丢失原始文件中的数据;
  2. 始终可以毫无问题地生成您想要的结果;
  3. 永远不会将整个文件加载到内存中(如readlines()所做);
  4. 不关心您找到结果的行索引(尽管您可以使用enumerate上的f来获取结果)。
  5. 成功完成后,您可以手动删除原始文件(或使用os.remove / shutil.rmtree)。忘记文件内编辑,虽然它起初看起来更直观。如果您害怕在此过程中留下大量临时文件,请使用tempfile等适当的工具。