简体   繁体   English

在 Python 中编辑 *.dat 文件特定行的特定部分

[英]Editing a specific part of specific line of *.dat file in Python

The line 5163 is 10,0.3 .线 5163 是10,0.3 This code written below edits the whole line to 5,0.3 .下面编写的这段代码将整行编辑为5,0.3 I want to just replace number 10 to 5 without replacing the whole line.我只想将10号替换为5 号而不替换整条线。 I want to edit that specific part.我想编辑那个特定的部分。 How can this be done?如何才能做到这一点?

import os
import time

with open('Job-1.dat', 'rt') as fin:
    with open('out.dat', 'wt') as fout:
        for i, line in enumerate(fin):
            if i == 5163:
                fout.write(' 5, 0.3\n')
            else:
                fout.write(line)

os.remove('Job-1.dat')
time.sleep(5)
os.rename('out.inp', 'Job-1.inp')

Change:改变:

        if i == 5163:
            fout.write(' 5, 0.3\n')

to:至:

        if i == 5163:
            items = line.split(',')
            out = ','.join(['10'] + items[1:])
            fout.write(out)

You can keep the last part of the line by replacing only what you want to replace:您可以通过仅替换要替换的内容来保留该行的最后一部分:

# your code
        for i, line in enumerate(fin):
            if i == 5163:
                modified = line.replace("10,", "5,")
                fout.write(modified + '\n')
            else:
                fout.write(line)

# etc

See str.replace .请参阅str.replace

As @Blotosmetek mentioned, adding a '\n' to each line (wich already contains one at the end) will lead to empty lines in your output file - in case thats not wanted, use正如@Blotosmetek 提到的,在每一行添加一个'\n' (最后已经包含一个)将导致output 文件中的空行 - 如果不需要,请使用

    fout.write(modified) # no extra '\n' added

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

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