python - 更改特定行中的特定值(例如行号 :57) and saving the file with same file name using python

标签 python

import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
    i=1
    for line in fileinput.input(file, inplace=1):        
        if i==57:
            if searchExp in line:
                line = line.replace(searchExp,replaceExp)
            sys.stdout.write(line)
        i+=1
replaceAll("5MW_Platform_karbarge.DAT","22.0","23.0")

此代码正在运行,问题是执行后文件中的其余行丢失。任何人都可以建议修改,以便除了第 57 行之外,文件的其余部分不受干扰吗?非常感谢。

最佳答案

你的问题是你只将第57行写回到文件中,只需将sys.stdout.write移出if i==57,这样每一行都会被写入,但只有57行被替换。

这应该有效

import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
    i=1
    for line in fileinput.input(file, inplace=1):        
        if i==57:
            if searchExp in line:
                line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)
        i+=1
replaceAll("5MW_Platform_karbarge.DAT","22.0","23.0")

关于python - 更改特定行中的特定值(例如行号 :57) and saving the file with same file name using python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35886078/

相关文章:

python - 有没有 len(someObj) 没有调用 someObj 的 __len__ 函数的情况?

python - 仅重命名 Pandas 数据框中的最后一列(考虑重复标题)

python - Factory Boy 与 Django ManyToMany 模型

Python 正则表达式 findall 到输出文件

Python:OOP 开销?

python - 散点图的 Y 轴始终从 0 开始

python - 如何修复旨在解决行列式的函数?

python - 如果列表项以 '.' 开头,为什么 python3 不从列表创建文件夹?

python - 有没有办法使用矢量化来操作 3D 数组和 1D 数组?

python - 地理编码器不可用 : HTTPSConnectionPool error for some addresses using geopy and Nominatim